在python中,以字符串形式获取系统命令的输出
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19243020/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
in python, get the output of system command as a string
提问by S4M
In python I can run some system command using os or subprocess. The problem is that I can't get the output as a string. For example:
在 python 中,我可以使用 os 或 subprocess 运行一些系统命令。问题是我无法将输出作为字符串。例如:
>>> tmp = os.system("ls")
file1 file2
>>> tmp
0
I have an older version of subprocess that doesn't have the function check_out, and I would prefer a solution that doesn't require to update that module since my code will run on a server I don't have full admin rights.
我有一个没有函数 check_out 的旧版本子进程,我更喜欢不需要更新该模块的解决方案,因为我的代码将在我没有完全管理员权限的服务器上运行。
This problem seems trivial, yet I couldn't find a trivial solution
这个问题看起来微不足道,但我找不到微不足道的解决方案
采纳答案by Hari Menon
Use os.popen()
:
使用os.popen()
:
tmp = os.popen("ls").read()
The newer way (> python 2.6) to do this is to use subprocess
:
执行此操作的较新方法(> python 2.6)是使用subprocess
:
proc = subprocess.Popen('ls', stdout=subprocess.PIPE)
tmp = proc.stdout.read()