質問

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:

import os
n=raw_input("enter cmd")
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 n.

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.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top