【问题标题】:python calling an external cmd and redirect stdout to filepython调用外部cmd并将stdout重定向到文件
【发布时间】:2012-10-12 08:14:08
【问题描述】:

错误信息:

Failed to open output_file_path/**.txt

代码:

cmd = 'showTxt "%s" > "%s"' % (file_path, output_file_path)
LoggerInstance.log('[cmd] '+cmd)

#os.system(cmd)
splited_cmd=shlex.split(cmd)

p = subprocess.Popen(splited_cmd, stderr=subprocess.PIPE)
#p.wait()
output = p.stderr.read()
print output

LoggerInstance.log('[console std error]'+ output)

如何将标准输出重定向到 cmd 中的文件?

【问题讨论】:

  • output_file_path的值是多少?
  • Popen(splited_cmd, stdout=open(output_file_path, "w"), stderr=subprocess.PIPE)
  • 据我所知,您不能在调用的命令中使用管道,您必须创建两个子进程并将一个的粗壮用作另一个的标准输入。太复杂!要么使用 python 将 stout 保存到文件中,要么将命令放入 shell 脚本并使用子进程调用该文件。
  • @AntoinePelisse 感谢 antoine 它有效,你能把它作为答案吗?

标签: python stdout stderr windows-console


【解决方案1】:

您可以将file-handler 作为stdout 参数提供给Popen,即:

p = subprocess.Popen(splited_cmd,
                     stderr=subprocess.PIPE,
                     stdout=open(output_file_path, "w"))

当然,准备好捕获它可以抛出的异常。

【讨论】:

    猜你喜欢
    • 2010-11-28
    • 2014-07-22
    • 1970-01-01
    • 1970-01-01
    • 2021-09-08
    • 2012-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多