繁体   English   中英

在 Python 中,如何同时从主脚本运行另一个 Python 脚本并在停止主脚本时将其关闭?

[英]In Python, how can I run another Python script from the main script at the same time and close it when I stop the main script?

import subprocess 

subprocess.Popen('python', 'second_script.py')

这会打开第二个脚本并使它们同时运行吗? 如果我停止主脚本,它还会关闭第二个脚本吗? 如果没有,我该怎么做?

我不清楚你需要什么。

如果你想在另一个脚本“pythonScriptB.py”中使用一些在“pythonScriptA.py”中编码的函数,你可以导入第一个脚本:

from pythonScriptA import *

# Use the functions in the ScriptB

如果您希望两个脚本同时/并行运行,您应该查看多处理库,或者查看允许 python 代码在多个线程上运行的任何其他库。

-- 编辑:更正脚本

你应该做这样的事情

#! /usr/bin/env python3

import subprocess

pid = subprocess.Popen(['second-script']).pid
print(f'pid={pid}')
...
# do whatever you have to do here

暂无
暂无

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

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