[英]How to pass command-line arguments to a python script from within another script?
I've got a python script that is named code.py
and this takes two command line arguments --par_value xx --out_dir /path/to/dir
where par_value
is a certain parameter and out_dir
is the output directory.我有一个名为
code.py
的 python 脚本,这需要两个命令行 arguments --par_value xx --out_dir /path/to/dir
其中par_value
是某个参数, out_dir
是 Z78E6221F6393D1356814CE6.DB33 I want to run this script for different values of the input parameter.我想为输入参数的不同值运行此脚本。
So I want to use the array:所以我想使用数组:
par_vector = np.array([1,2,3])
and have the output file for each named, say, "output_1", "output_2" and "output_3".并为每个命名的 output 文件,例如“output_1”、“output_2”和“output_3”。 So I'm trying to write a python script where I can create that array above and an array of output strings, say, called
output_strings
so I can automatically run something along the like:所以我正在尝试编写一个 python 脚本,我可以在其中创建上面的数组和一个 output 字符串数组,比如说,称为
output_strings
,这样我就可以自动运行类似的东西:
for i,j in zip(par_vector, output_strings):
python code.py --par_value i --out_dir j
But this does not run so I'm unable to figure out how to make such an automation of my code work rather than repeatedly calling the script code.py
from the terminal.但这并没有运行,所以我无法弄清楚如何使我的代码自动化工作,而不是从终端重复调用脚本
code.py
Any advice is welcome!欢迎任何建议!
It might be a bit convoluted, but a way you could do it is to generate either .bat
or .sh
files (depending on your operating system) and call them with Popen
from the subprocess
library.这可能有点复杂,但您可以这样做的一种方法是生成
.bat
或.sh
文件(取决于您的操作系统)并使用subprocess
库中的Popen
调用它们。
from subprocess import Popen, PIPE
for i,j in zip(par_vector, output_strings):
cmd = """python code.py --par_value {} --out_dir {}""".format(i,j)
temp_filename = "{}{}.bat".format(i,) #swap .bat for .sh if not on Windows
with open(temp_filename, 'wb') as out_file:
out_file.write(cmd)
execution = Popen([temp_filename], stdout=PIPE, stderr=PIPE)
results = execution.communicate()
# add conditions based on the output generated by results if you want to use it to verify, etc.
os.remove(temp_filename)
Obviously this needs to be changed to match your exact needs for the file name and location, etc..显然,这需要更改以匹配您对文件名和位置等的确切需求。
I would use os.system
for this if you're OK with the fact that os.system()
is blocking.如果您对
os.system()
阻塞的事实感到满意,我会为此使用os.system
。 This would look something like:这看起来像:
import os
for i,j in zip(par_vector, output_strings):
os.system(f"python code.py --par_value {i} --out_dir {j}")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.