运行 python 来自另一个 python 脚本的脚本,但不是子进程
Run python script from another python script but not as an child process
是否可以从另一个 python 脚本 运行 一个 python 脚本而不等待终止。
子进程创建后父进程将立即终止。
我试过了:
subprocess.Popen([sys.executable, "main.py"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
还有:
os.system(...)
您只需添加 &
即可在后台启动脚本:
import os
os.system('/path/to/script.sh &')
exit()
在这种情况下,即使主 Python 脚本退出,启动的 shell 脚本仍将继续工作。
但请记住,它可能会导致僵尸进程出现在我们的系统中。
如果您知道另一个 Python 脚本有一个 main
方法,您可以简单地在代码中调用该另一个脚本:
import main
...
exit(main.main())
但是这里另一个脚本是在调用脚本的上下文中执行的。如果你想避免它,你可以使用 os.exec...
函数,通过启动一个新的 Python 解释器:
import os
...
os.execl(sys.executable, "python", 'main.py')
exec 系列函数将替换(在 Unix-Linux 下)当前的 Python 解释器。
是否可以从另一个 python 脚本 运行 一个 python 脚本而不等待终止。
子进程创建后父进程将立即终止。
我试过了:
subprocess.Popen([sys.executable, "main.py"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
还有:
os.system(...)
您只需添加 &
即可在后台启动脚本:
import os
os.system('/path/to/script.sh &')
exit()
在这种情况下,即使主 Python 脚本退出,启动的 shell 脚本仍将继续工作。 但请记住,它可能会导致僵尸进程出现在我们的系统中。
如果您知道另一个 Python 脚本有一个 main
方法,您可以简单地在代码中调用该另一个脚本:
import main
...
exit(main.main())
但是这里另一个脚本是在调用脚本的上下文中执行的。如果你想避免它,你可以使用 os.exec...
函数,通过启动一个新的 Python 解释器:
import os
...
os.execl(sys.executable, "python", 'main.py')
exec 系列函数将替换(在 Unix-Linux 下)当前的 Python 解释器。