0
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?

Gru
  • 817
  • 13
  • 20

1 Answers1

1

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

maininformer
  • 967
  • 2
  • 17
  • 31
  • When I added shell=True, the terminal becomes unresponsive.(Stops executing exactly at that line.) Is there any other way around it other than using files in python(As it can be slow). – Gru Jan 13 '19 at 09:04
  • What version of python are you using and what do you mean by "any other way around it other than using files i python"? are you trying to tail a message log? what are you trying to achieve? – maininformer Jan 13 '19 at 09:23
  • I want to grab the last line of the file. I dont want to use file = open("/home/sourabh/sanju.txt",r). As I would be calling this python file .bashrc. I did not want to use the default File I/O of python. I'm using python 2.7 . Apparently if I use ["ls", "-la"] instead of above in check_output , it throws no error. Only for the tail command its throwing this error. – Gru Jan 13 '19 at 09:28
  • The edited answer works for me on Python 2.7.10. so I am not sure why it breaks for you. Note that there will be no outputs as you are assigning it to a variable. That being said, the reason "ls" works is that it does not need your files system like tail does. There are some ways to do it in pure python, see here: https://stackoverflow.com/questions/3346430/what-is-the-most-efficient-way-to-get-first-and-last-line-of-a-text-file – maininformer Jan 13 '19 at 09:37
  • I am also trying to print the variable but the error is being thrown at the check_output line. This is strange as I had created a new environment in anaconda and tried, still the same error. I'll check out your reference thanks. – Gru Jan 13 '19 at 12:01
  • got it to work using the link you have mentioned. I will edit my question with the attached link. Thanks a lot..! – Gru Jan 13 '19 at 12:42