开发者

os.system or subprocess to pass command to shell

开发者 https://www.devze.com 2023-03-31 03:44 出处:网络
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:

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 m开发者_Python百科ost examples are as of yet beyond my current understanding.


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()


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消