【问题标题】:subprocess.CalledProcessError : No such file or directory. Even though the file existssubprocess.CalledProcessError :没有这样的文件或目录。即使文件存在
【发布时间】:2019-01-13 07:10:06
【问题描述】:
tail: cannot open 'home/sourabh/sanju.txt' for reading: No such file or directory

Traceback (most recent call last):
  File "/home/sourabh/resizeWindow.py", line 23, in <module>
    line = subprocess.check_output(['tail', '-1', 'home/sourabh/sanju.txt']).split(' ')[3:]

  File "/usr/lib/python2.7/subprocess.py", line 223, in check_output
    raise CalledProcessError(retcode, cmd, output=output)

subprocess.CalledProcessError: Command '['tail', '-1', 'home/sourabh/sanju.txt']' returned non-zero exit status 1

我已经交叉检查了文件是否存在,甚至故意创建了一个文件。

我的 python 代码中的确切行是:

line = subprocess.check_output(['tail', '-1', 'home/sourabh/sanju.txt']).split(' ')[3:]

编辑:正如@PlumnSemPy 所述,此链接解决了我的问题:

What is the most efficient way to get first and last line of a text file?

【问题讨论】:

    标签: python python-2.7 subprocess call


    【解决方案1】:

    试试:

    line = subprocess.check_output(['tail -1 home/sourabh/sanju.txt'], shell=True).split(' ')[3:]
    

    但请注意此处的警告:https://docs.python.org/2/library/subprocess.html#frequently-used-arguments

    【讨论】:

    • 当我添加 shell=True 时,终端变得无响应。(在该行完全停止执行。)除了在 python 中使用文件之外还有其他方法吗(因为它可能很慢)。
    • 您使用的是什么版本的python,“除了使用python文件之外的任何其他方式”是什么意思?您是否要跟踪消息日志?你想达到什么目标?
    • 我要抓取文件的最后一行。我不想使用 file = open("/home/sourabh/sanju.txt",r)。因为我会调用这个 python 文件 .bashrc。我不想使用 python 的默认文件 I/O。我正在使用 python 2.7 。显然,如果我在 check_output 中使用 ["ls", "-la"] 而不是上面的,它不会引发错误。只有tail命令才会抛出这个错误。
    • 编辑后的答案适用于我在 Python 2.7.10 上。所以我不确定为什么它会为你打破。请注意,当您将其分配给变量时,不会有任何输出。话虽如此,“ls”起作用的原因是它不需要像tail那样的文件系统。在纯 python 中有一些方法可以做到这一点,请参见此处:stackoverflow.com/questions/3346430/…
    • 我也在尝试打印变量,但在 check_output 行抛出了错误。这很奇怪,因为我在 anaconda 中创建了一个新环境并尝试过,仍然是同样的错误。我会检查你的参考谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-03
    • 1970-01-01
    • 1970-01-01
    • 2021-07-21
    相关资源
    最近更新 更多