11

I'm looking for a quick bash script or program that will allow me to kick off a python script in a separate process. What's the best way to do this? I know this is incredibly simple, just curious if there's a preferred way to do it.

asked Jun 2, 2010 at 1:49
1
  • 1
    It appears that you mean "process". Please update your question. Commented Jun 2, 2010 at 2:29

4 Answers 4

23

Just use the ampersand (&) in order to launch the Python process in the background. Python already is executed in a separate process from the BASH script, so saying to run it "in a separate thread" doesn't make much sense -- I'm assuming you simply want it to run in the background:

#! /bin/bash
python path/to/python/program.py &

Note that the above may result in text being printed to the console. You can get around this by using redirection to redirect both stdout and stderr to a file. For example:

#! /bin/bash
python path/to/python/program.py > results.txt 2> errors.log &
answered Jun 2, 2010 at 1:57
Sign up to request clarification or add additional context in comments.

2 Comments

Where you say "stdin" I assume you mean "stderr" and it should be 2>errors.log (without the ampersand after the "2").
Yah, this is what I was expecting. Thanks!
8

The best way to do this is to do it in python! Have a look at the multiprocess libraries.

Here is a simple example from the links above:

from multiprocessing import Process
def f(name):
 print 'hello', name
if __name__ == '__main__':
 p = Process(target=f, args=('bob',))
 p.start()
 p.join()
answered Jun 2, 2010 at 1:55

Comments

4

bash doesn't really do threads -- it does do processes just fine, though:

python whatever.py &

the & at the end just means "don't wait for the subprocess to end" -- bash will execute the command itself in a separate process anyway, it's just that normally it waits for that separate process to terminate (all Unix shells work that way since time immemorial).

answered Jun 2, 2010 at 1:55

Comments

2

Your jargon is all confused. But in bash you can run a process in the background by appending a &:

print foo.py &
answered Jun 2, 2010 at 1:55

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.