Python 如何将系统调用输出重定向到字符串
可能重复:Python 如何将系统调用输出重定向到字符串,python,unix,system-calls,Python,Unix,System Calls,可能重复: 我正在运行一个python程序: import os os.system("ls") # ls command runs on the terminal 要将输出存储在文件中,请执行以下操作: os.system("ls > a.txt") 我需要的是,它将输出存储在一些临时字符串中。这可能吗 import subprocess output = subprocess.Popen(["ls"], stdout = subprocess.PIPE, stderr = su
我正在运行一个python程序:
import os
os.system("ls") # ls command runs on the terminal
要将输出存储在文件中,请执行以下操作:
os.system("ls > a.txt")
我需要的是,它将输出存储在一些临时字符串中。这可能吗
import subprocess
output = subprocess.Popen(["ls"], stdout = subprocess.PIPE, stderr = subprocess.STDOUT).communicate()[0]
在这里,您运行外部命令ls
,并将命令的stderr
和stdout
strewams重定向到变量output
其中必须重定向的流是使用Popen
函数的参数stdout
和stderr
指定的
在这里,您运行外部命令ls
,并将命令的stderr
和stdout
strewams重定向到变量output
其中必须重定向的流是使用
Popen
函数的参数stdout
和stderr
指定的 不,你不能那样做。系统调用后,将a.txt的内容读入变量。最好还是使用python管道。@SridharJagannathan你错了。当然,您可以使用python的子流程模块来实现这一点。@BigYellowCactus我提到过pipes.No。你不能那样做。系统调用后,将a.txt的内容读入变量。最好还是使用python管道。@SridharJagannathan你错了。当然,您可以使用python的子流程模块来实现这一点。@BigYellowCactus我提到过管道。