I need to run the command date | grep -o -w '"+tz+"'' | wc -w
using Python on my localhost. I am using subprocess
module for the same and using the check_output
method as I need to capture the output for the same.
However it is throwing me an error :
Traceback (most recent call last):
File "test.py", line 47, in <module>
check_timezone()
File "test.py", line 40, in check_timezone
count = subprocess.check_output(command)
File "/usr/lib/python2.7/subprocess.py", line 537, in check_output
process = Popen(stdout=PIPE, *popenargs, **kwargs)
File "/usr/lib/python2.7/subprocess.py", line 679, in __init__
errread, errwrite)
File "/usr/lib/python2.7/subprocess.py", line 1249, in _execute_child
raise child_exception-
OSError: [Errno 2] No such file or directory
You have to add
shell=True
to execute a shell command.check_output
is trying to find an executable called:date | grep -o -w '"+tz+"'' | wc -w
and he cannot find it. (no idea why you removed the essential information from the error message).See the difference between:
And:
Read the documentation about the Frequently Used Arguments for more information about the
shell
argument and how it changes the interpretation of the other arguments.Note that you should try to avoid using
shell=True
since spawning a shell can be a security hazard (even if you do not execute untrusted input attacks like Shellshock can still be performed!).The documentation for the subprocess module has a little section about replacing the shell pipeline. You can do so by spawning the two processes in python and use
subprocess.PIPE
:You can write some simple wrapper function to easily define pipelines:
With this in place you can write
pipeline('date | grep 1')
orpipeline('date', 'grep 1')
orpipeline(['date'], ['grep', '1'])
The most common cause of FileNotFound with subprocess, in my experience, is the use of spaces in your command. Use a list, instead.
This change results in no more FileNotFound errors, and is a nice solution if you got here searching for that exception with a simpler command. If you are using python 3.5 or greater, try using this approach:
You should see how one command's output becomes another's input just like using a shell pipe, but you can easily debug each step of the process in python. Using subprocess.run is recommended for python > 3.5, but not available in prior versions.