Search code examples
pythonpython-2.7subprocesscall

subprocess.CalledProcessError : No such file or directory. Even though the file exists


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

I have crossed checked if the file exists and even intentionally created a file.

The exact line in my python code is:

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

Edit: As mentioned by @PlumnSemPy this link solves my problem:

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


Solution

  • Try:

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

    But heed to the warning here: https://docs.python.org/2/library/subprocess.html#frequently-used-arguments