简体   繁体   English

使用“开始”将输出从python子进程调用写入文件

[英]write output to file from python subprocess call with 'start'

I'm trying to redirect an output from a shell window opened from a python script - to a file. 我正在尝试将通过python脚本打开的shell窗口中的输出重定向到文件。

So, after some googling, I came up with this code: 因此,经过一番谷歌搜索后,我想到了以下代码:

file_output = open(MS_Log + 'LOGS.txt', 'w+')
subprocess.call('start ' + URL_logs, shell=True, stdout=file_output)

This does indeed opens a new shell window and runs the command I want in it. 实际上,这确实会打开一个新的Shell窗口并在其中运行我想要的命令。 However, the output is printed on the screen (inside that new shell window) and not to the file. 但是,输出被打印在屏幕上(在新的Shell窗口内)而不是文件。

I want it to be both - printed in the shell window and saved to file. 我希望两者兼有-在shell窗口中打印并保存到文件。

Now, the command I run there is continuous, it runs until stopped with Ctrl+C, so I think this might be the problem...? 现在,我在那里运行的命令是连续的,一直运行到用Ctrl + C停止为止,所以我认为这可能是问题所在...? Maybe if it will be closed gracefully it will dump it's contents to the file? 也许它会被优雅地关闭,然后将其内容转储到文件中?

You can try to save the output in a variable and then write this in a file: 您可以尝试将输出保存到变量中,然后将其写入文件中:

process = subprocess.Popen(command, stdout = subprocess.PIPE, shell = True)
(process_output,  error) = process.communicate()
file = open(path_of_file_output, "w")
file.write(process_output)
file.close()

OP, I adapted a good solution from this question . OP,我为此问题改编了一个好的解决方案。

It should show the output of your command in terminal and save it to file while running. 它应该在终端中显示命令的输出, 在运行时将其保存到文件中。 That means it'll work for infinite loops as well. 这意味着它也适用于无限循环。 It doesn't use the shell=True option that leaves you open to shell injection (always set tight permissions on a script that uses shell=True if you're not just playing on your LAN at home). 它不使用shell=True选项使您可以进行shell注入(如果您不只是在家中玩LAN,请始终对使用shell=True的脚本设置严格的权限)。 The solution has one weakness: it only works if there are newlines in your output; 该解决方案有一个缺点:它仅在输出中包含换行符时才有效; if not, nothing will be printed/written. 否则,将不会打印/书写任何内容。

import subprocess

""" continuously print command output and append it to file while running """

def run(command):    
    popen = subprocess.Popen(command, stdout=subprocess.PIPE)
    return iter(popen.stdout.readline, b"")

filename = "subprocess_output"
f = open(filename, "a")

for line in run(["/bin/bash", "infinite_loop.sh"]):
    print(line), # the comma keeps python from adding an empty line
    f.write(line)

f.close()

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

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