繁体   English   中英

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

[英]Exporting console output to a .txt doesn't work

我正在尝试将控制台输出从Script1.py保存到.txt文件。 但是,我需要针对多个参数运行此脚本,例如“ python Script1.py 43131”,其中“ 43131”是参数,并且参数存储在列表中(Runnummer)。 我现在想做的是使用典型的bash导出执行另一个脚本“ WrapperScript1.py”为我做这些事情:

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,但是我并没有真正使用它的方法,因此我像上面一样尝试过。 我也尝试过os.system,但是也没有用。

提前致谢!

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

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

注释中所述 (感谢@tripleee), {0..100}范围是Bash功能,因此它不适用于所有shell。 如果您的外壳不支持括号扩展,则可以for i in $(seq 0 100)使用seq工具,否则,可以使用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参数设置为True

此外,您正在混合两种调用约定。 传递单个字符串供外壳程序解析,或者将已解析标记的列表作为字符串传递。

from subprocess import call
for i in range(len(Runnummer)):    
    call("python Script1.py " + Runnummer[i] + 
      ' > ' + './test/Run' + Runnummer[i] +'.txt', shell=True)

由于无论如何您都在调用shell,因此,如Tom的answer所建议的那样,改为在shell脚本中执行此操作可能更有意义。

第一件事是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 ,只需直接在列表上进行迭代即可。 所以:

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

不要在外壳中使用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)

另外,直接在列表上进行迭代(而不是在用作列表索引的整数列表上进行迭代)更干净。

暂无
暂无

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

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