【问题标题】:python: trying to understand "subprocess" O/S calls [closed]python:试图理解“子进程”O/S调用[关闭]
【发布时间】:2015-12-02 18:10:37
【问题描述】:

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

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

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

-) 最重要的是:我如何在 python 中获取与某个正则表达式匹配的最新文件的名称?我的想法是向 python 提供诸如“ls -rt $REGEX | head -1”之类的内容,但 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
...

【问题讨论】:

  • 为什么要使用外部进程来列出文件?这是mywiki.wooledge.org/ParsingLs,绝对是。
  • 一次一个问题。
  • 你告诉它运行一个名为“ls -rt”的命令
  • @stark:我试图让它执行“ls -rt”,考虑到引号,这应该是唯一的一件事;但显然它试图扮演自作聪明。哦,好吧。
  • @tripleee:我正在尝试我能想到的唯一方法。请参阅我的最后一点:我很乐意考虑任何其他 python 编码来获取名称与某些正则表达式匹配的最新文件的名称。感谢您的思考。

标签: python regex subprocess


【解决方案1】:

"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 将 shell 命令的输出作为字符串返回。但是您确实希望避免将外部进程用于在 Python 中轻松完成的任务。也许作为你想要的一个微不足道的修复print(subprocess.check_output(["ls", "-rt", "."]))

【讨论】:

  • @KarelAdams,是正则表达式还是全局模式? (*foo* 是一个 glob 模式,而不是正则表达式;如果这是您想要的,请使用 fnmatch Python 模块)。
  • 查看更新,使用 mtime 代码。也许在发布后续问题之前先谷歌一下。
  • @KarelAdams,如果您的“一行 bash”正在使用 ls -t,那么它就有问题了。请参阅mywiki.wooledge.org/BashFAQ/003——健壮可靠的 bash 比草率、错误的 bash 更长,就像 Python 也比草率、错误的 bash 更长。 :)
  • 与(太)琐碎的 Bash 解决方案不同,这个解决方案可以开箱即用地处理带有换行符的文件名。具有该功能的 Bash 解决方案将至少与此 Python 代码一样长,而且更加晦涩难懂。同时,它很容易适应更复杂的场景,具有健全的异常处理和错误报告。
  • newest = max(os.listdir(os.curdir), key=os.path.getmtime)。相关:How do you get a directory listing sorted by creation date in python?
猜你喜欢
  • 2013-07-19
  • 1970-01-01
  • 2011-12-30
  • 2017-04-08
  • 2018-06-30
  • 2017-05-02
  • 2017-01-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多