python:试图理解 "subprocess" O/S 调用

python: trying to understand "subprocess" O/S calls

请在下面的对话框中帮助解决很多问题:

-) 为什么 "subprocess.check_output(["ls","-rt","."])" 没有输出,尽管至少被接受了?

-) 为什么 "subprocess.check_output(["ls -rt","."]) " 根本不被接受?

-) 最重要的是:我如何在 python 中获取与某些正则表达式匹配的最新文件的名称?我的想法是将 "ls -rt $REGEX | head -1" 之类的东西提供给 python,但是 python 似乎非常不喜欢这种方法..?

karel@suske:~/home_shared/develop/airnav_db$ python --version
Python 2.7.6
karel@suske:~/home_shared/develop/airnav_db$ python -c 'import subprocess ; subprocess.check_output(["ls -rt","."])'
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/usr/lib/python2.7/subprocess.py", line 566, in check_output
    process = Popen(stdout=PIPE, *popenargs, **kwargs)
  File "/usr/lib/python2.7/subprocess.py", line 710, in __init__
    errread, errwrite)
  File "/usr/lib/python2.7/subprocess.py", line 1327, in _execute_child
    raise child_exception
OSError: [Errno 2] No such file or directory
karel@suske:~/home_shared/develop/airnav_db$ python -c 'import subprocess ; subprocess.check_output(["ls","-rt","."])'
karel@suske:~/home_shared/develop/airnav_db$ ls -l
total 52
drwxrwxrwx 2 karel users 4096 Oct 11  2009 auxdata
...

"ls -rt" 不是有效命令的名称,所以这就是您的第二种情况失败的原因。 "ls" 与参数 "-rt""." 工作正常,只是没有在您期望的地方产生输出。但无论如何,你应该循环 os.listdir('.') 而不是。

when = 0
for name in os.listdir('.'):
    if not 'foo' in name:
        continue
    # name matches *foo*
    st = os.stat(name)
    if st.mtime > when:
        when = st.mtime
        newest = name
print newest

如果您确实需要,这应该很容易扩展到正则表达式;但是对于大多数繁琐的任务来说,它们确实有点过分了。

作为记录,subprocess.check_output returns shell 命令的输出为字符串。但是你真的想避免使用外部进程来完成在 Python 中很容易完成的任务。也许你想要 print(subprocess.check_output(["ls", "-rt", "."]))

作为一个微不足道的修复