1

我想使用 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

4 回答 4

2

不要使用commands; 它已被弃用,实际上对您的目的没有用。改为使用subprocess

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

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

于 2012-11-11T21:39:00.213 回答
0

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

import sh

bin = sh.Command("/usr/local/bin/fio/fioverify.fio")
handle = bin(_bg=True)
# ... do other code ...
handle.wait()
于 2012-11-12T05:48:19.507 回答
0

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

于 2012-11-11T21:37:48.353 回答
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")
于 2016-07-07T14:05:43.297 回答