简体   繁体   English

在Python脚本中,运行目录中的所有Python脚本并流输出

[英]From a Python script, run all Python scripts in a directory and stream output

My file structure looks like this: 我的文件结构如下所示:

runner.py
scripts/
    something_a/
        main.py
        other_file.py
    something_b/
        main.py
        anythingelse.py
    something_c/
        main.py
    ...

runner.py should look at all folders in scripts/ in run the main.py located there. runner.py应该在scripts/中运行的main.py查看所有文件夹。

Right now I'm achieving this through subprocess.check_output . 现在,我通过subprocess.check_output实现此目的。 It works, but some of these scripts take a long time to run and I don't get to see any progress; 它可以工作,但是其中一些脚本需要很长时间才能运行,我看不到任何进展。 it prints everything after the process has finished. 该过程完成后,它将打印所有内容。

I'm hoping to find a solution that allows for 2 things to be done somewhat easily: 我希望找到一种解决方案,使某些事情可以轻松完成:

1) Stream the output instead of getting it all at the end 1)流式传输输出,而不是一无所有

2) Doesn't prohibit running multiple scripts at once 2)不禁止一次运行多个脚本

Is this possible? 这可能吗? A lot of the solutions I've seen for running a Python script from another require knowledge of the other script's name/location. 我见过的很多用于从另一个脚本运行Python脚本的解决方案都需要了解另一个脚本的名称/位置。 I can also enforce that all the main.py 's have a specific function if that helps. 如果有帮助,我可以强制所有main.py都具有特定功能。

You could use Popen to loop through each file and write its content to multiple log files. 您可以使用Popen遍历每个文件,并将其内容写入多个日志文件。 Then, you could read from these files in real-time, while each one is populated. 然后,您可以实时读取这些文件,同时填充每个文件。 :) :)

How you would want to translate the output to a more readable format, is a little bit more tricky because of readability. 由于易读性,您希望如何将输出转换为更易读的格式。 You could create another script which reads these log files, with Popen, and decide on how you'd like this information read back in a understandable manner. 您可以使用Popen创建另一个读取这些日志文件的脚本,并决定您希望如何以可理解的方式回读这些信息。

""" Use the same command as you would do for check_output """
cmd = ''

for filename in scriptList:
   log = filename + ".log"
   with io.open(filename, mode=log) as out:
        subprocess.Popen(cmd, stdout=out, stderr=out)

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

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