简体   繁体   English

运行后如何在后台启动 python 脚本?

[英]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?当我的脚本运行时,我怎样才能使它立即作为后台进程运行 main() ? 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.操作系统将为您处理;)当然,如果这是在 windows 或 *nix 上,您将不得不 state。

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...如果您在 windows 下运行此程序,您可能需要检查cmd.exe程序 - 我认为有一个选项可以将其 arguments 作为后台进程运行...

Or if you are running this under linux machine, you can check the process by using ps aux | grep yourpythonscript.py或者如果你在 linux 机器下运行这个,你可以使用ps aux | grep yourpythonscript.py检查进程。 ps aux | grep yourpythonscript.py

On Windows, run the program using pythonw.exe instead of python.exe .在 Windows 上,使用pythonw.exe而不是python.exe运行程序。

On Unix and MacOS, use the Python daemon recipe or the python-daemon package.在 Unix 和 MacOS 上,使用Python 守护程序配方或 python-守护python-daemon package。

I would use the Python threading library.我会使用 Python线程库。 This will allow you to run main() in the background.这将允许您在后台运行 main()。

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 &在 linux 中,您可以使用 & 在后台运行它,如果您希望它运行,即使您关闭 shell 使用 nohup 命令: nohup python yourpythonscript.py &

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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