When using python's sh module (not a part of stdlib), I can call a program in my path as a function and run it in the background:
from sh import sleep
# doesn't block
p = sleep(3, _bg=True)
print("prints immediately!")
p.wait()
print("...and 3 seconds later")
And I can use sh's Command
wrapper and pass in the absolute path of an executable (helpful if the executable isn't in my path or has characters such as .
):
import sh
run = sh.Command("/home/amoffat/run.sh")
run()
But trying to run the wrapped executable in the background, as follows:
import sh
run = sh.Command("/home/amoffat/run.sh", _bg=True)
run()
Fails with a traceback error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: __init__() got an unexpected keyword argument '_bg'
How can I run an executable wrapped by sh.Command
in the background? Looking for an elegant solution.
EDIT:
I used the python interpreter for testing passing _bg
to the command (not the wrapper), which I now realize is a bad way to test for blocking and non-blocking processes:
>>> 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
With hello.py being as follows:
#!/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()
Instead, do
import sh
run = sh.Command("/home/amoffat/run.sh")
run(_bg=True)
(BTW, the subprocess
module provides a much less magical way to do such things.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With