如何将 os.system() 输出存储在 python 中的变量或列表中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19267591/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 13:17:55  来源:igfitidea点击:

How to store os.system() output in a variable or a list in python

pythonpython-2.7ssh

提问by Jitu

I am trying to get the output of a command by doing ssh on a remote server using below command.

我试图通过使用以下命令在远程服务器上执行 ssh 来获取命令的输出。

os.system('ssh user@host " ksh .profile; cd dir; find . -type f |wc -l"')

Output of this command is 14549 0

此命令的输出为 14549 0

why is there a zero in the output ? is there any way of storing the output in variable or list ? I have tried assigning output to a variable and a list too but i am getting only 0 in the variable. I am using python 2.7.3.

为什么输出中有一个零?有没有办法将输出存储在变量或列表中?我也尝试将输出分配给一个变量和一个列表,但我在变量中只得到 0。我正在使用 python 2.7.3。

采纳答案by Paul

There are many good SO links on this one. try Running shell command from Python and capturing the outputor Assign output of os.system to a variable and prevent it from being displayed on the screenfor starters. In short

关于这一点有很多很好的 SO 链接。尝试从 Python 运行 shell 命令并捕获os.system的输出将输出分配给变量,并防止它显示在屏幕上以供初学者使用。简而言之

import subprocess
direct_output = subprocess.check_output('ls', shell=True) #could be anything here.

The shell=True flag should be used with caution:

应谨慎使用 shell=True 标志:

From the docs: Warning

来自文档:警告

Invoking the system shell with shell=True can be a security hazard if combined with untrusted input. See the warning under Frequently Used Arguments for details.

如果与不受信任的输入结合使用,使用 shell=True 调用系统 shell 可能会带来安全隐患。有关详细信息,请参阅常用参数下的警告。

See for much more info: http://docs.python.org/2/library/subprocess.html

有关更多信息,请参见:http: //docs.python.org/2/library/subprocess.html

回答by Lorenzo Gatti

If you are calling os.system() in an interactive shell, os.system() prints the standard output of the command ('14549', the wc -l output), and then the interpreter prints the result of the function call itself (0, a possibly unreliable exit code from the command). An example with a simpler command:

如果您在交互式 shell 中调用 os.system(),则 os.system() 打印命令的标准输出('14549',wc -l 输出),然后解释器打印函数调用本身的结果(0,来自命令的可能不可靠的退出代码)。一个更简单的命令示例:

Python 3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:06:53) [MSC v.1600 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.system("echo X")
X
0
>>>

回答by Simon

To add to Paul's answer (using subprocess.check_output):

添加到保罗的答案(使用 subprocess.check_output):

I slightly rewrote it to work easier with commands that can throw errors (e.g. calling "git status" in a non-git directory will throw return code 128 and a CalledProcessError)

我稍微重写了它,以便使用可能引发错误的命令更轻松地工作(例如,在非 git 目录中调用“git status”将引发返回代码 128 和 CalledProcessError)

Here's my working Python 2.7 example:

这是我的工作 Python 2.7 示例:

import subprocess

class MyProcessHandler( object ):
    # *********** constructor
    def __init__( self ):
        # return code saving
        self.retcode = 0

    # ************ modified copy of subprocess.check_output()

    def check_output2( self, *popenargs, **kwargs ):
        # open process and get returns, remember return code
        pipe = subprocess.PIPE
        process = subprocess.Popen( stdout = pipe, stderr = pipe, *popenargs, **kwargs )
        output, unused_err = process.communicate( )
        retcode = process.poll( )
        self.retcode = retcode

        # return standard output or error output
        if retcode == 0:
            return output
        else:
            return unused_err

# call it like this
my_call = "git status"
mph = MyProcessHandler( )
out = mph.check_output2( my_call )
print "process returned code", mph.retcode
print "output:"
print out

回答by stingray

you can use os.popen().read()

您可以使用 os.popen().read()

import os
out = os.popen('date').read()

print out
Tue Oct  3 10:48:10 PDT 2017