Python 的 sh 模块 - 在后台运行命令包装器



使用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"
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模块提供了一种不那么神奇的方式来做这些事情。)

最新更新