sam*_*kgp 0 python unix system-calls
可能重复:
管道子进程标准输出到变量
我正在运行python程序:
import os
os.system("ls") # ls command runs on the terminal
Run Code Online (Sandbox Code Playgroud)
要将输出存储在文件中:
os.system("ls > a.txt")
Run Code Online (Sandbox Code Playgroud)
我需要的是,它将输出存储在一些临时字符串中.那可能吗 ??
import subprocess
output = subprocess.Popen(["ls"], stdout = subprocess.PIPE, stderr = subprocess.STDOUT).communicate()[0]
Run Code Online (Sandbox Code Playgroud)
在这里,您运行外部命令ls并重定向无论是stderr和stdout命令变量的strewams output.
必须使用参数stdout和函数指定必须重定向流stderr的位置Popen.