Execute shell command and retrieve stdout in Python

nowox

In Perl, if I want to execute a shell command such as foo, I'll do this:

#!/usr/bin/perl
$stdout = `foo`

In Python I found this very complex solution:

#!/usr/bin/python
import subprocess
p = subprocess.Popen('foo', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
stdout = p.stdout.readlines()
retval = p.wait()

Is there any better solution ?

Notice that I don't want to use call or os.system. I would like to place stdout on a variable

Hooting

An easy way is to use sh package. some examples:

import sh
print(sh.ls("/"))

# same thing as above
from sh import ls
print(ls("/"))

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

using ffmepg in python, shell and stdout

来自分类Dev

在python,shell和stdout中使用ffmepg

来自分类Dev

emacs:如何从dired-do-shell-command捕获stdout?

来自分类Dev

How to execute a shell command with root permission from swift

来自分类Dev

执行shell命令并在Python中检索stdout

来自分类Dev

如何使用subprocess.call从Python Shell exec拦截stdout?

来自分类Dev

Find files and execute command

来自分类Dev

Shell.StdOut.ReadAll返回的垃圾字符

来自分类Dev

stdout从shell获取先前的1行以上

来自分类Dev

最小化对shell命令stdout的依赖

来自分类Dev

python ssh stdout多个

来自分类Dev

python ssh stdout多个

来自分类Dev

Shell Execute的安静MSI Exec

来自分类Dev

HBase Shell command questions

来自分类Dev

ADODB Command.Execute超时

来自分类Dev

retrieve a word after a regular expression in shell script

来自分类Dev

如何使stdout与Parallel Python兼容?

来自分类Dev

Python stdout.readline()冻结

来自分类Dev

Python未记录到stdout

来自分类Dev

Python stdout.readline()冻结

来自分类Dev

从python到stdin java的stdout

来自分类Dev

在python中对齐stdout打印

来自分类Dev

Python stdout重定向(特殊)

来自分类Dev

在if语句中输出Command Shell

来自分类Dev

.command之后“退出”到shell

来自分类Dev

Cygwin can't execute shell script

来自分类Dev

简单的shell linux C实现,使用freopen重定向stdout

来自分类Dev

如何判断命令或Shell脚本的输出是stdout还是stderr

来自分类Dev

Shell:两个命令的STDIN / STDOUT的相互管道