如何在python中使用命令模块在后台运行命令?

时间:2012-11-11 21:33:44

标签: python background-process

我想使用python 2.7在后台运行系统命令,这就是我所拥有的:

import commands
path = '/fioverify.fio'

cmd= "/usr/local/bin/fio" + path + " "+ " &"
print cmd
handle = commands.getstatusoutput(cmd)

这失败了。如果我删除了号&&它就可以了。我需要在后台运行一个命令(/usr/local/bin/fio/fioverifypath)。

有关如何完成此任务的任何指示?

4 个答案:

答案 0 :(得分:2)

不要使用commands;它已被弃用,实际上并不适用于您的目的。请改用subprocess

fio = subprocess.Popen(["/usr/local/bin/fio", path])

与您的进程并行运行fio命令,并将变量fio绑定到进程的句柄。然后,您可以调用fio.wait()等待进程完成并检索其返回状态。

答案 1 :(得分:0)

使用subprocess模块,subprocess.Popen允许您作为子进程运行命令(在后台)并检查其状态。

答案 2 :(得分:0)

您也可以尝试sh.py,它支持后台命令:

import sh

bin = sh.Command("/usr/local/bin/fio/fioverify.fio")
handle = bin(_bg=True)
# ... do other code ...
handle.wait()

答案 3 :(得分:0)

使用Python 2.7

在后台运行进程

commands.getstatusoutput(...)不够聪明,无法处理后台流程,请使用subprocess.Popenos.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")