【问题标题】:Running multiple Python scripts from a single parent script从单个父脚本运行多个 Python 脚本
【发布时间】:2016-06-01 09:45:38
【问题描述】:

我想一次运行多个脚本(大约 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]

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

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

【问题讨论】:

    标签: python subprocess multiprocessing


    【解决方案1】:

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

    test.py

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

    main.py

    import test
    
    test.main()
    

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

    test1.py

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

    main.py

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

    【讨论】:

    • 您好,感谢您的回复,问题是脚本位于其他文件夹中,我提供的只是一个测试。其次,没有任何功能,它是一个相对简单的脚本(用于查询、API 和存储数据)我会用它来语法吗?同样很明显,这些方法(线程)仅在脚本返回时才显示脚本的输出,例如我不能让它打印我在脚本中的打印语句?顺便说一句,该脚本位于“while True”循环中,因此永远不会返回任何内容。我将在 EDIT 中粘贴脚本的副本
    猜你喜欢
    • 1970-01-01
    • 2021-12-19
    • 2020-10-08
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    • 1970-01-01
    • 2016-09-03
    • 1970-01-01
    相关资源
    最近更新 更多