I am trying to execute a command in a shell and pipe the output at the same time for filtering.
the relevent code looks like:
os.system(n + ' | grep x')
the result is
Syntax error: Redirection unexpected.
It is on ubuntu, seemed like some references online mentioned this, but none I could directly associate. Seems like subprocess may help, but most examples are as of yet beyond my current understanding.
In Ubuntu, the default shell is
dash, and that is the error it gives you if you start a line with
|, so I'm guessing you didn't put anything in
os.system() is deprecated now. The
subprocess module is much more powerful and preferred. You would have to invest some time in reading the docs on it, but it pays off. It has some handy "convenience functions" to reduce the work needed.
Use subprocess module instead of os.system, which is deprecated.
subprocess allows piping and capturing stdout, as you want.
process = subprocess.call(command_string.split(), ..., stdout=subprocess.PIPE, ...) ... handle your output from process.communicate()
You are getting an error from the shell, not python. You most likely did not enter a command, so the system call was only " | grep x", which would return an error such as that.