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

如何在python中将os.system()输出存储在变量或列表中,python,python-2.7,ssh,Python,Python 2.7,Ssh,我试图通过使用下面的命令在远程服务器上执行ssh来获得命令的输出 os.system('ssh user@host " ksh .profile; cd dir; find . -type f |wc -l"') 此命令的输出为14549 0 为什么输出中有一个零? 有没有办法将输出存储在变量或列表中?我也尝试过将输出分配给一个变量和一个列表,但变量中只有0。我使用的是python 2.7.3。如果在交互式shell中调用os.system(),os.system()会打印命令的标准输出(“1

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

os.system('ssh user@host " ksh .profile; cd dir; find . -type f |wc -l"')
此命令的输出为14549 0

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

如果在交互式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
>>>

在这一个上有很多好的SO链接。先试试看。总之

import subprocess
direct_output = subprocess.check_output('ls', shell=True) #could be anything here.
应谨慎使用shell=True标志:

从文档中: 警告

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

有关更多信息,请参见:

添加到Paul的答案中(使用子流程。检查输出):

我稍微重写了它,以便更轻松地处理可能抛出错误的命令(例如,在非git目录中调用“git status”将抛出返回代码128和被调用的进程错误)

下面是我的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
您可以使用
os.popen().read()


如果您使用的是Python2.7,那么请使用
子流程
模块,而不是
os.system
。可能的重复,我觉得这并没有回答问题。我的输出有以下字符:b'Fri Nov 27 14:20:49 CET 2020\n'。b'和\n'之间。你知道为什么会这样吗@paul如果我使用os.system,它不会出现,但我无法将其保存在var@Shalomi11是,b表示返回的数据是字节而不是字符。有关更完整的处理方法,请参见此:。总之,需要对其进行解码以从字节返回字符串(例如,b'abc'.decode('utf8'))。换行符就是如何从正在使用的底层命令返回输出。请参阅以进行讨论
import os
out = os.popen('date').read()

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