【问题标题】:write output to file from python subprocess call with 'start'使用'start'从python子进程调用将输出写入文件
【发布时间】:2016-07-18 01:19:46
【问题描述】:

我正在尝试将从 python 脚本打开的 shell 窗口的输出重定向到文件。

所以,经过一番谷歌搜索,我想出了以下代码:

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

这确实会打开一个新的 shell 窗口并在其中运行我想要的命令。但是,输出会打印在屏幕上(在新的 shell 窗口内)而不是文件。

我希望它同时打印在 shell 窗口中并保存到文件中。

现在,我在那里运行的命令是连续的,它一直运行到 Ctrl+C 停止,所以我认为这可能是问题......?也许如果它会优雅地关闭它会将其内容转储到文件中?

【问题讨论】:

标签: python file subprocess call stdout


【解决方案1】:

您可以尝试将输出保存在变量中,然后将其写入文件中:

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

【讨论】:

  • 也许添加一行关于为什么shell = True 可能是一个安全问题?
  • 他希望输出显示在终端中,如果你不想显示输出你把Shell = False 和解决
  • 谢谢@Miguel Jiménez。我尝试了这段代码(使用简单的回显,而不是复杂的命令,所以我可以确定它结束了),但它仍然没有写入文件。 process = subprocess.Popen('start echo hello', stdout = subprocess.PIPE, shell = True) (process_output,  error) = process.communicate() file = open('LOGS.txt', "w") file.write(process_output) file.close()
  • 你为什么写start echo hello?你只写echo hello。 Popen 执行终端命令,这里的“start”这个词不正确。
  • @MiguelJiménez OP 似乎在 Windows 系统上,start 是一个有效命令,您猜对了,它启动了一个外部进程/程序。 More on that here。我在 *nix 系统上,我假设你也是,因为 echo hello 在 shell/bash 中有效。
【解决方案2】:

OP,我从 this question 改编了一个很好的解决方案。

它应该在终端中显示您的命令输出在运行时将其保存到文件中。这意味着它也适用于无限循环。它不使用shell=True 选项让您对shell 注入开放(如果您不只是在家中玩LAN,请始终在使用shell=True 的脚本上设置严格的权限)。 该解决方案有一个弱点:它仅在输出中有换行符时才有效;如果不是,则不会打印/写入任何内容。

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

【讨论】:

  • 谢谢,我会在几分钟内尝试并更新结果!
  • 这确实创建了一个文件并写入它,但是,当我将“开始”添加到命令提示符时它停止工作(我需要它来打开一个新的 CMD 窗口)。我想我可能只是使用这个解决方案(如果我不知道如何让它像我想要的那样工作),只是弹出一个 CMD 窗口仅用于显示目的,即我将运行该命令两次 - 一次在新的CMD 窗口,一次没有新窗口 - 只是为了保存输出。
  • @AlexyGrabov 可能有办法做到这一点,但我仍然没有找到完美的解决方案。另一方面,为什么需要打开另一个终端窗口而不是将输出保留在运行脚本的窗口中?
  • 因为我想打开 3-4 个窗口,并在所有窗口中显示不同的滚动日志。如果我在一个窗口中执行此操作会很混乱:)
猜你喜欢
  • 1970-01-01
  • 2016-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多