How to start a python script in the background onc

2019-04-02 19:24发布

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.

4条回答
该账号已被封号
2楼-- · 2019-04-02 19:41

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 &

查看更多
Melony?
3楼-- · 2019-04-02 19:50

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

查看更多
Viruses.
4楼-- · 2019-04-02 19:55

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.

查看更多
Lonely孤独者°
5楼-- · 2019-04-02 20:04

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

查看更多
登录 后发表回答