相关疑难解决方法(0)

将输出命令重定向到变量或文件?

我正在尝试编写一个python脚本,它允许我从命令中获取输出并将其放入文件或变量(Preferability a variable).

在我的代码中,我已将输出重定向到StringIO()对象.从那里,我想要输出一个命令并将其放入该StringIO()对象.

以下是我的代码示例:

from StringIO import StringIO
import sys

old_stdout = sys.stdout

result = StringIO()
sys.stdout = result

# This will output to the screen, and not to the variable
# I want this to output to the 'result' variable
os.system('ls -l')
Run Code Online (Sandbox Code Playgroud)

另外,我如何获取结果并将其放入字符串?

提前致谢!!

python command-line output

2
推荐指数
1
解决办法
3058
查看次数

标签 统计

command-line ×1

output ×1

python ×1