我试图将控制台输出从Script1.py保存到.txt文件。然而,我需要运行这个脚本的几个参数,例如:"python Script1.py 43131",其中"43131"是参数,参数存储在列表中(Runnummer)。我现在要做的是执行另一个脚本"WrapperScript1.py",使用典型的bash导出为我做这些事情:
from subprocess import call
for i in range(len(Runnummer)):
call(["python Script1.py " + Runnummer[i] +
' > ' + './test/Run' + Runnummer[i] +'.txt'])
此代码现在应该执行"python Script1.py arg(i)> ./test/runarg(i).txt"。我已经在控制台中手动尝试了一个I,它可以工作,但不知何故,如果我使用子进程并循环它就不起作用了。实际情况是,代码正常运行,但没有将控制台输出保存到.txt文件中。
我读到你也可以在子进程中使用PIPE,但我不知道如何使用它,所以我像上面一样尝试了一下。我也试过。系统,但也不工作。
提前感谢!
假设您事先知道要运行循环的次数,则可以使用shell而不是从一个python脚本调用另一个python脚本:
for i in {0..100}; do python Script1.py $i > test/Run$i.txt; done
正如评论中提到的(感谢@tripleee), {0..100}
范围是Bash的一个特性,所以它不会在所有shell中工作。如果您的shell不支持大括号展开,您可以使用seq
工具for i in $(seq 0 100)
,或者使用while
循环:
i=0
while [ $i -le 100 ]; do
python Script1.py $i > test/Run$i.txt
i=$((i+1)) # POSIX compliant (thanks @chepner)
# or, for a more vintage experience
# i=$(expr $i + 1)
done
重定向是shell的一个特性。如果需要使用,需要将shell
参数设置为True
。
而且,你混合了两种调用约定。要么传递一个字符串供shell解析,要么传递一个已解析的令牌列表作为字符串。
from subprocess import call
for i in range(len(Runnummer)):
call("python Script1.py " + Runnummer[i] +
' > ' + './test/Run' + Runnummer[i] +'.txt', shell=True)
由于无论如何都要调用shell,因此在shell脚本中执行此操作可能更有意义,正如Tom的回答所建议的那样。
第一件事是call
期望一个参数数组
call
不要重定向为shell所以你不能使用>
对于子进程的收集输出,更简单的是使用check_output
代替
from subprocess import check_output
Runnummer=["a","b"]
for i in range(len(Runnummer)):
with open('./test/Run' + Runnummer[i] +'.txt',"w") as output:
output.write(check_output(["python","Script1.py",str(Runnummer[i])]))
从python风格点95%的时间不需要range
,只需要直接迭代list。所以:
from subprocess import check_output
Runnummer=["c","d"]
for run in Runnummer:
with open('./test/Run' + run +'.txt',"wb") as output:
output.write(check_output(["python","Script1.py",run]))
您可以使用os.system
代替subprocess
:
import os
for i in range(len(Runnummer)):
os.system('python Script1.py ' + Runnummer[i] +
' > ' + './test/Run' + Runnummer[i] +'.txt')
不是在shell中使用I/O重定向,而是打开一个文件以用Python编写,并使用stdout
参数将文件句柄传递给call
。
from subprocess import call
for f in Runnummer:
output_file = "./test/Run{0}.txt".format(f)
with open(output_file, "w") as fh:
call(["python", "Script1.py", f], stdout=fh)
而且,直接遍历列表比遍历作为列表索引的整数列表更简洁。