简体   繁体   English

如何批量执行一系列Python脚本?

[英]How to execute a series of Python scripts in batch?

I frequently find that I need to run a series of python scripts sequentially. 我经常发现我需要按顺序运行一系列python脚本。 The order and number of these scripts may vary, but instead of executing each script individually and sequentially, is there a preferred way of batch automating a series of Python scripts? 这些脚本的顺序和数量可能会有所不同,但是有没有一种首选的方式可以批量自动化一系列Python脚本,而不是逐个依次执行每个脚本? My programs require multiple and complex file path and other argument combinations. 我的程序需要多个复杂的文件路径以及其他参数组合。

Refactor them into modules, then make a new script that import s the relevant functions from each module and runs those. 将它们重构为模块,然后创建一个新脚本,该脚本从每个模块import相关功能并运行这些功能。

The easiest way to do this is to write a main function per module and run all the main function serially. 最简单的方法是为每个模块编写一个main功能,然后依次运行所有main功能。

I think larsmans' option is the best by far. 我认为larsmans的选择是迄今为止最好的选择。 But if there is a reasons you cannot or should not turn them into easily imported modules, it is quite easy to just make a .bat file in Windows (or .ps1 if you have powershell) which calls each of them in turn. 但是,如果由于某种原因您不能或不应该将它们转换为易于导入的模块,则很容易在Windows中制作一个.bat文件(如果具有powershell,则创建一个.ps1),然后依次调用它们。 In Linux, the same thing can be done with bash or csh as long as you remember to make the resulting batch executable. 在Linux中,只要您记得使生成的批处理文件可执行,就可以用bash或csh完成相同的操作。

If you want another python script that calls them as though they were being called from a command line (in order to pass in the argument combinations without refactoring them into modules) you can readily use os.system or the more powerful (but sligtly more complicated) subprocess module . 如果您想要另一个python脚本来调用它们,就像从命令行中调用它们一样(以便传递参数组合而不将它们重构为模块),则可以轻松使用os.system或功能更强大的脚本 (但更加复杂) ) 子处理模块

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

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