我有两个脚本 Server.py 和 ServerGUI.py。我希望它们独立并行运行。假设我制作了另一个脚本 main.py。如何从 main.py 运行 Server.py 和 ServerGUI.py?
你能给我推荐main.py的代码吗?
最佳答案
要从 python 脚本中运行 2 个或更多脚本,您可以使用带有 nohup 的子进程包。这将在后台运行每个脚本,允许您从同一源脚本并行运行它们。此外,作为一个选项,此示例会将每个脚本的标准输出保存在不同的文件中
import os
from subprocess import call
from subprocess import Popen
# subprocess.call(['python', 'exampleScripts.py', somescript_arg1, somescript_val1,...]).
Popen(['nohup', 'python', 'exampleScripts.py'],
stdout=open('null1', 'w'),
stderr=open('logfile.log', 'a'),
start_new_session=True )
Popen(['nohup', 'python', 'exampleScripts.py'],
stdout=open('null2', 'w'),
stderr=open('logfile.log', 'a'),
start_new_session=True )
Popen(['nohup', 'python', 'exampleScripts.py'],
stdout=open('null3', 'w'),
stderr=open('logfile.log', 'a'),
start_new_session=True )
输出:每个脚本的开始和结束时间重叠,显示第二个脚本在第一个脚本结束之前开始
(ds_tensorflow) C:\DataScience\SampleNotebooks\Threading>python RunScripts.py
(ds_tensorflow) C:\DataScience\SampleNotebooks\Threading>cat null*
2020-07-13 15:46:21.251606
List processing complete.
2020-07-13 15:46:29.130219
2020-07-13 15:46:22.501599
List processing complete.
2020-07-13 15:46:31.227954
2020-07-13 15:46:23.758498
List processing complete.
2020-07-13 15:46:32.431079
如果您想将代码保存在一个地方,您也可以对函数使用相同的想法。此示例将并行运行两个不同的函数两次。
函数示例:
...
import threading
...
def some_function()
# code
def other_function()
# code
if __name__ == "__main__":
jobs = []
#same function run multiple times
threads = 2
for i in range(0, threads):
out_list = list()
thread1 = threading.Thread(target=some_function(size, i, out_list))
jobs.append(thread1)
thread2 = threading.Thread(target=other_function(size, i, out_list))
jobs.append(thread2)
# Start the threads (i.e. calculate the random number lists)
for j in jobs:
j.start()
# Ensure all of the threads have finished
for j in jobs:
j.join()
# continue processing
关于python - 从python中的单个脚本运行多个脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62870725/