Question

I have a python script, which should execute a shell script. But it should sleep 30 seconds before executing. I want the script to sleep in the background and then execute it.

The Shell Command should be like this: If I type this command directly to the console, it works.

(sleep 30 && /root/bin/myscript.sh parameter1 parameter2) > /dev/null 2>&1

Now from python: (I have divided the commands)

subprocess.call(['/bin/sleep', '30', '&'])
subprocess.call(['/root/bin/myscript.sh', str(dom), str(limit), '&'])

(str(dom) and str(limit) are the 2 parameters)

I get this error:

/bin/sleep: invalid time interval `&'

Why does it take & as parameter instead of 30?

Was it helpful?

Solution

The error is because & is being passed to the /bin/sleep command as an argument, whereas you are using it in the context of telling the shell to execute the command in the background.

If you want to use '&' or '&&' you can use os.system:

os.system('sleep 1 && echo foo && sleep 5 && echo bar')

or to run nonblocking (in the background) you can use the standard &:

os.system('sleep 1 && echo foo && sleep 5 && echo bar &')

OTHER TIPS

You can't do what you are wanting to do, force a python script to run in the background every time. Python also can't run a task directly in the background. You might look into Threading, which might accomplish what you want, but without knowing why you want to go back to the command prompt, it's difficult. I think what you might want is a threading timer specifically, an example of which can be found here.

from threading import Timer

def hello():
    print "hello, world"

t = Timer(30.0, hello)
t.start() # after 30 seconds, "hello, world" will be printed

How about

subprocess.Popen(["sh","-c","sleep 30; /root/bin/myscript.sh parameter1 parameter2"])

You can build the command line for parameter1, parameter2 using string concatenation.

But as described in PearsonArtPhoto's answer, using thread is better option.

Call with one string:

prc = subprocess.Popen('/bin/sleep 3; echo Some string', shell=True)

Note, I remove &.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top