1
def main(self,argv):
    do stuff.......

if __name__ == '__main__':
    main(sys.argv[1:])

When my script is run, how can I cause it to immediately run main() as a background process? It will run to completion and outputs information to a file.

I forgot to say...the goal is to be able to run this on any OS. I do not want to modify the way the script is called in the command line, I want the script itself to cause it to run in the background.

Takkun
  • 8,119
  • 13
  • 38
  • 41
  • You want to run your script as a daemon ? check pypi from package that can help you with that : http://pypi.python.org/pypi?%3Aaction=search&term=daemon&submit=search , i never use anyone of those so i can't recommend anyone . – mouad Jun 14 '11 at 14:46

4 Answers4

3

easy:

$ python yourpythonscript.py &

The os will handle that for you ;) Of course, you will have to state if this is on windows or *nix.

If you are running this under windows, you might want to check the cmd.exe program - I think there is an option there for running its arguments as a background process...

Or if you are running this under linux machine, you can check the process by using ps aux | grep yourpythonscript.py

Aditya Kresna Permana
  • 11,869
  • 8
  • 42
  • 48
Daren Thomas
  • 67,947
  • 40
  • 154
  • 200
  • I'd like to note that it *really* pays off to learn the common unix command line tools. Even for windows developers like me: With cygwin on your dev box, tons of problems that surround your main development effort can be solved. New hot tools this week: `sed`, `uniq`, `sort` and `comm`. – Daren Thomas Jun 23 '11 at 07:09
3

On Windows, run the program using pythonw.exe instead of python.exe.

On Unix and MacOS, use the Python daemon recipe or the python-daemon package.

Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
1

I would use the Python threading library. This will allow you to run main() in the background.

silent1mezzo
  • 2,814
  • 4
  • 26
  • 46
  • Threading isn't useful to put the whole process in the background. The shell will block until the main process exits, so you need to fork off a new process. – Sven Marnach Jun 14 '11 at 15:25
0

In linux You could use & to run it on background and if you want it to be run even if you close that shell use nohup command: nohup python yourpythonscript.py &

hamed
  • 1,325
  • 1
  • 15
  • 18