You can use the subprocess module in Python to run a long running command in the background. Here's an example:

import subprocess

# run the command in the background
process = subprocess.Popen(['command', 'arg1', 'arg2'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)

# check if the command is still running
while process.poll() is None:
    # do some other work here
    print("Command is still running...")

# check if the command was successful
if process.returncode == 0:
    print("Command was successful!")
else:
    print("Command failed with exit code", process.returncode)

In this example, the subprocess.Popen() function is used to start the command in the background. The stdout and stderr arguments are set to subprocess.PIPE to capture the output of the command.

The process.poll() function is used to check if the command is still running. This function returns None while the command is running, and the exit code of the command once it has finished.

Finally, the process.returncode attribute is used to check if the command was successful (i.e. returned an exit code of 0). If the command failed, the exit code will be non-zero and can be printed for debugging purposes

how to use python to run a long running command in background and check the command successfully

原文地址: https://www.cveoy.top/t/topic/cwGu 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录