Files
Obsidian-Main/21. 資料收集/Programming/Python/subprocess.md

1.8 KiB
Raw Blame History

subprocess.Popen

import subprocess

process = subprocess.Popen(['echo', 'More output'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = process.communicate()
stdout, stderr

Input arguments is a list. Notice communicate() will block until process was finished. And the output string stdout and stderr is of type byte. You can convert the output to string by:

new_string = stdout.decode('utf-8')

or use universal_newlines=True in subprocess.Popen(). Example:

process = subprocess.Popen(['ping', '-c 4', 'python.org'], 
                           stdout=subprocess.PIPE,
                           universal_newlines=True)

The .poll() will return the exit code of process. If process is still running. .poll() will return None. Example:

process = subprocess.Popen(['ping', '-c 4', 'python.org'], stdout=subprocess.PIPE, universal_newlines=True)

while True:
    output = process.stdout.readline()
    print(output.strip())
    # Do something else
    return_code = process.poll()
    if return_code is not None:
        print('RETURN CODE', return_code)
        # Process has finished, read rest of the output 
        for output in process.stdout.readlines():
            print(output.strip())
        break

參考:

subprocess.run

subprocess.run()subprocess.Popen()是一樣的行為,差別是subprocess.run()會在process執行完畢之後才return也就是說流程會被block住。 subprocess.run()會回傳一個型別是subprocess.CompletedProcess的object.


參考: