简体   繁体   中英

How to start a python script in the background once it's run?

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.

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 ps aux | grep yourpythonscript.py

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.

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

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 &

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM