subprocess.CalledProcessError:没有这样的文件或目录。即使文件存在

时间:2019-01-13 07:10:06

标签: python python-2.7 subprocess call

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?

1 个答案:

答案 0 :(得分: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