当前位置: 动力学知识库 > 问答 > 编程问答 >

python - os.system or subprocess to pass command to shell

问题描述:

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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: