这里是我的代码:Python的标准输出,得到以列表
rows = subprocess.check_output("ls -1t | grep 'syslogdmz'", shell=True)
结果我得到的是文件的2名,但我不明白为什么不把它们放在一个列表中。有没有办法做到这一点?
谢谢
这里是我的代码:Python的标准输出,得到以列表
rows = subprocess.check_output("ls -1t | grep 'syslogdmz'", shell=True)
结果我得到的是文件的2名,但我不明白为什么不把它们放在一个列表中。有没有办法做到这一点?
谢谢
从文档https://docs.python.org/2/library/subprocess.html#subprocess.check_output
“运行命令与参数,并返回其输出作为一个字节串。”
不知道为什么你期望得到一个清单。
请参考手册页。
>>> import subprocess
>>> help(subprocess.check_output)
Help on function check_output in module subprocess:
check_output(*popenargs, **kwargs)
Run command with arguments and return its output as a byte string.
If the exit code was non-zero it raises a CalledProcessError. The
CalledProcessError object will have the return code in the returncode
attribute and output in the output attribute.
The arguments are the same as for the Popen constructor. Example:
>>> check_output(["ls", "-l", "/dev/null"])
'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n'
The stdout argument is not allowed as it is used internally.
To capture standard error in the result, use stderr=STDOUT.
>>> check_output(["/bin/sh", "-c",
... "ls -l non_existent_file ; exit 0"],
... stderr=STDOUT)
'ls: non_existent_file: No such file or directory\n'
>>>
尝试使用os.popen
来获取列表中的输出。 或者使用split()进入列表。
x = os.popen('ls -1t | grep syslogdmz').readlines()
print x
您可能需要使用os.popen
:
from os import popen
rows = popen("ls -1t | grep 'syslogdmz'","r").readlines()
rows
将包含结果列表中。
这似乎工作,你不知道如何避免采取\ n而不必为每一行rstrip它。谢谢 – 2015-03-31 11:42:07
您可以使用'rows.splitlines()'获取字节字符串列表,而不是一个包含\ n的字符串。 – maahl 2015-03-31 09:07:17