【问题标题】:How to redirect system call output to a string [duplicate]如何将系统调用输出重定向到字符串[重复]
【发布时间】:2012-07-03 14:03:48
【问题描述】:

可能重复:
Pipe subprocess standard output to a variable

我正在运行一个 python 程序:

import os
os.system("ls") # ls command runs on the terminal 

将输出存储在文件中:

os.system("ls > a.txt")

我需要的是,它将输出存储在一些临时字符串中。这可能吗??

【问题讨论】:

  • 没有。你不能那样做。系统调用后将a.txt的内容读入变量。最好使用 python 管道。
  • @SridharJagannathan 你错了。当然你可以这样做,使用 python 的 subprocess 模块。
  • @BigYellowCactus 我确实提到了管道。

标签: python unix system-calls


【解决方案1】:
import subprocess
output = subprocess.Popen(["ls"], stdout = subprocess.PIPE, stderr = subprocess.STDOUT).communicate()[0]

在这里您运行外部命令ls 并将命令的stderrstdout 流重定向到变量output

使用Popen 函数的参数stdoutstderr 指定必须重定向流的位置。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-14
    • 2022-10-16
    相关资源
    最近更新 更多