使用 Python 2.7 在后台运行进程
commands.getstatusoutput(...)
不够聪明,无法处理后台进程,使用subprocess.Popen
或os.system
.
重现commands.getstatusoutput
后台进程如何失败的错误:
import commands
import subprocess
#This sleeps for 2 seconds, then stops,
#commands.getstatus output handles sleep 2 in foreground okay
print(commands.getstatusoutput("sleep 2"))
#This sleeps for 2 seconds in background, this fails with error:
#sh: -c: line 0: syntax error near unexpected token `;'
print(commands.getstatusoutput("sleep 2 &"))
subprocess.Popen 如何在后台进程上成功的演示:
#subprocess handles the sleep 2 in foreground okay:
proc = subprocess.Popen(["sleep", "2"], stdout=subprocess.PIPE)
output = proc.communicate()[0]
print(output)
#alternate way subprocess handles the sleep 2 in foreground perfectly fine:
proc = subprocess.Popen(['/bin/sh', '-c', 'sleep 2'], stdout=subprocess.PIPE)
output = proc.communicate()[0]
print("we hung for 2 seconds in foreground, now we are done")
print(output)
#And subprocess handles the sleep 2 in background as well:
proc = subprocess.Popen(['/bin/sh', '-c', 'sleep 2'], stdout=subprocess.PIPE)
print("Broke out of the sleep 2, sleep 2 is in background now")
print("twiddling our thumbs while we wait.\n")
proc.wait()
print("Okay now sleep is done, resume shenanigans")
output = proc.communicate()[0]
print(output)
os.system 如何处理后台进程的演示:
import os
#sleep 2 in the foreground with os.system works as expected
os.system("sleep 2")
import os
#sleep 2 in the background with os.system works as expected
os.system("sleep 2 &")
print("breaks out immediately, sleep 2 continuing on in background")