这是我的代码:
rows = subprocess.check_output("ls -1t | grep 'syslogdmz'", shell=True)
我得到的结果是两个文件名,但我不明白它为什么不把它们放在一个列表中。有办法吗?
谢谢
答案 0 :(得分:2)
您可能想要使用os.popen
:
from os import popen
rows = popen("ls -1t | grep 'syslogdmz'","r").readlines()
rows
会将结果包含在列表中。
答案 1 :(得分:0)
来自文档https://docs.python.org/2/library/subprocess.html#subprocess.check_output
“使用参数运行命令并将其输出作为字节字符串返回。”
不确定为什么要获得列表。
答案 2 :(得分:0)
请参阅手册页。
>>> 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