将控制台输出导出到.txt文件不起作用

2024-04-18 07:09:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将控制台输出从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”。 我已经在控制台中手动尝试过了,但如果我使用子进程并在其上循环,它就不起作用了。 代码正常运行,但没有控制台输出保存到.txt文件。你知道吗

我读到,你也可以使用管道从子流程,但我真的不知道如何使用它,所以我试着像上面。我也试过了操作系统但效果不太好。你知道吗

提前谢谢!你知道吗


Tags: 文件代码frompytesttxt脚本bash
3条回答

第一件事是call需要一个参数数组

第二件事是call不要重定向为shell,这样就不能使用>

对于子进程的gather输出,更简单的方法是使用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])]))

从pythonic风格的角度来看,95%的时间range是不需要的,只需直接在列表上迭代即可。所以:

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]))

假设您事先知道要运行循环的次数,您可以使用shell,而不是从另一个python脚本调用一个python脚本:

for i in {0..100}; do python Script1.py $i > test/Run$i.txt; done

正如前面提到的in the comments(感谢@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's answer中所建议的那样。你知道吗

相关问题 更多 >