Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python's sh module - Running Command wrapper in background

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"
like image 414
billyw Avatar asked Feb 14 '14 18:02

billyw


1 Answers

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.)

like image 186
Mike Graham Avatar answered Nov 14 '22 20:11

Mike Graham