Skip to main content
 首页 » 编程设计

python之从单个父脚本运行多个 Python 脚本

2024年10月24日11pengyingh

我想一次运行多个脚本(大约 15 个),我假设我可以使用子进程库来执行此操作,但我对此没有任何经验。

我目前正在玩这个脚本:

import os 
from subprocess import * 
 
#run child script 1 
p = Popen([r'D:\python\loanrates\test\test.py', "test"], shell=True, stdin=PIPE, stdout=PIPE) 
output = p.communicate() 
print output 
 
#run child script 2 
p = Popen([r'D:\python\loanrates\test\test2.py', "test2"], shell=True, stdin=PIPE, stdout=PIPE) 
output = p.communicate() 
print output 

它尝试运行的每个 python 脚本都很简单(用于测试目的)

import time  
 
for i in range(50): 
    print i  
    time.timer(1) 

这是正确的吗?这是在运行每个脚本吗?它运行没有错误

('', None) 
('', None) 
[Finished in 0.3s] 

如果是这样,我需要在子脚本中更改什么以便父脚本打印输出?或者类似地,我需要在父级中更改什么以便它在子级中打印打印功能?

编辑:我正在运行的脚本在不同的文件夹中 s a pastebin for the actual scripts ,每个都因 URL 中看到的 API 调用的后缀而异。没有函数,也没有返回代码将在 while True 循环中连续运行

请您参考如下方法:

如果您知道其他脚本的路径,则可以将它们作为模块导入并运行它们的方法

测试.py

def main(): 
    print "Hello, World!" 

主要.py

import test 
 
test.main() 

如果你想同时执行它们,使用线程。

测试1.py

def main(name): 
    print "Goodbye, %s!"%name 

主要.py

import test,test1 
from threading import Thread 
 
Thread(target=test.main).start() 
Thread(target=test1.main,args='user').start()