Python sh模块 - 在后台运行Command包装器

时间:2014-02-14 18:22:47

标签: python background-process

当使用python的sh模块(不是stdlib的一部分)时,我可以将路径中的程序作为函数调用并在后台运行:

from sh import sleep

# doesn't block
p = sleep(3, _bg=True)
print("prints immediately!")
p.wait()
print("...and 3 seconds later")

我可以使用sh的Command包装并传入可执行文件的绝对路径(如果可执行文件不在我的路径中或者包含.等字符,则会有帮助):

import sh
run = sh.Command("/home/amoffat/run.sh")
run()

但是尝试在后台运行包装的可执行文件,如下所示:

import sh
run = sh.Command("/home/amoffat/run.sh", _bg=True)
run()

因跟踪错误而失败:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: __init__() got an unexpected keyword argument '_bg'

如何在后台运行sh.Command包装的可执行文件?寻找一个优雅的解决方案。

编辑:

我使用python解释器来测试将_bg传递给命令(而不是包装器),我现在意识到这是测试阻塞和非阻塞进程的一种不好的方法:

>>> import sh
>>> hello = sh.Command("./hello.py")
>>> hello(_bg=True) # 5 second delay before the following prints and prompt is returned
HI
HI
HI
HI
HI

hello.py如下:

#!/usr/bin/python

import time

for i in xrange(5):
    time.sleep(1)
    print "HI"

1 个答案:

答案 0 :(得分:6)

import sh
run = sh.Command("/home/amoffat/run.sh", _bg=True) # this isn't your command, 
                                                   # so _bg does not apply
run()

相反,做

import sh
run = sh.Command("/home/amoffat/run.sh")
run(_bg=True)

(顺便说一下,subprocess模块提供了一种不那么神奇的方式来做这些事情。)