当使用Python的sh模块(不是标准库的一部分)时,我可以将路径中的程序作为函数调用并在后台运行:
如何在后台运行由
编辑:
我使用Python解释器测试将
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"