Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/339.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将系统调用输出重定向到字符串_Python_Unix_System Calls - Fatal编程技术网

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我提到过管道。