gpt4 book ai didi

python - 计时和重定向子进程 :PIPE output to file

转载 作者:太空宇宙 更新时间:2023-11-04 12:01:46 26 4
gpt4 key购买 nike

我正在尝试执行 bash 并想将 shell 上的输出重定向到一个文件

这是我目前的情况

baby = subprocess.Popen('some command', stdout = subprocess.PIPE, shell = True)
print (baby.stdout.readlines()) #i wanna see it in console
with open("log.txt","a") as fobj: #wanna create a file log.txt and save the output there as string
fobj.write(stdout)

但我收到此错误 NameError: name 'stdout' is not defined

我看过这些问题 Run subprocess and print output to logging , subprocess.Popen() doesn't redirect output to file , Can you make a python subprocess output stdout and stderr as usual, but also capture the output as a string?但无济于事,它们对我来说都太复杂了,我迷失在所有代码中......

我不能将 stdout 重定向到一个普通的 txt 文件吗?有没有一种方法可以构建一个函数来计时该脚本的执行并将其放入同一个 log.txt 文件中(我使用 time ./myscript.py 来计时,但我也不知道如何将它重定向到 txt 文件)

最佳答案

你应该根据自己的情况调整这个例子

首先创建input.txt文件

然后

import sys

with open(sys.argv[1], 'r') as input, open(sys.argv[2], 'w') as output:
for line in input:
output.write(str(line.strip()) + '\n')

你从命令行运行它(s4.py,你可以重命名它)

python s4.py input.txt output.txt

输出

obama
is
my boss

你可以猜到,但输出与输入相同。

关于python - 计时和重定向子进程 :PIPE output to file,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52145830/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com