简体   繁体   English

如何从命令行迭代和执行脚本?

[英]How to iterate and execute scripts from the command line?

I have a program that I run from the command line that takes two file arguments like this:我有一个从命令行运行的程序,它需要两个文件 arguments,如下所示:

$ my_program $我的程序

I would like to write a python script that can be used to run iterations of this program using different file arguments.我想编写一个 python 脚本,该脚本可用于使用不同的文件 arguments 运行该程序的迭代。 For example:例如:

$ my_program <file_1> <file_4>
$ my_program <file_2> <file_4>
$ my_program <file_3> <file_4>
...

I am trying to use the subprocess module from within python to run iterations of this program.我正在尝试使用 python 中的子进程模块来运行该程序的迭代。 What I can't seem to figure out is how I can iterate throguth different file arguments and then run each of these commands from the command line.我似乎无法弄清楚如何通过不同的文件 arguments 迭代,然后从命令行运行这些命令中的每一个。 Can anyone point me in the right direction or provide some example code that woudl explain how this could be done.谁能指出我正确的方向或提供一些示例代码来解释如何做到这一点。 Thanks in advance for the help!在此先感谢您的帮助!

From what I gather, you want something like this:从我收集的信息来看,你想要这样的东西:

cmds = [path_to_program, arg1, arg2]
subprocess.Popen(cmds)

then if you want to iterate through many, something like:那么如果你想遍历很多,比如:

cmds = [('file1', 'file4'), ('file2', 'file4'), ('file3', 'file4')]
for arg1, arg2 in cmds:
    subprocess.Popen([path_to_program, arg1, arg2])
for fname in ('1', '2', '3'):
  do_something_with(['a', fname, 'b'])

Replace the sequence in the for loop and in the function call as desired.根据需要替换for循环和 function 调用中的序列。

It seems what you are looking for is to do a bash script.看来您正在寻找的是执行 bash 脚本。 There you can execute those commands like in a command line.在那里,您可以像在命令行中一样执行这些命令。

You could get in your main funcion and execute this too but it wouldn't be as flexible.你也可以进入你的主要功能并执行它,但它不会那么灵活。

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

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