472,378 Members | 1,286 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,378 software developers and data experts.

how to invoke the shell command and then get the result in python

Hi,

I want to do following: get a user input regex, then pass this as a
parameter to grep, and then get the result from grep.

Any code snip to implement the similar function? I am a python newbie.

Thanks a lot.
Bin

Dec 5 '06 #1
7 2613
Bin Chen wrote:
I want to do following: get a user input regex, then pass this as a
parameter to grep, and then get the result from grep.

Any code snip to implement the similar function? I am a python newbie.
import os
for line in os.popen("grep pattern *.txt"):
print line,

also see os.system and subprocess.

note that if you want to write portable code, you can implement your own
"grep" using the "re" module:

import re
p = re.compile(pattern)
for index, line in enumerate(open(filename)):
if p.match(line):
print index, line,

</F>

Dec 5 '06 #2


Fredrik Lundh wrote:
import os
for line in os.popen("grep pattern *.txt"):
print line,

also see os.system and subprocess.

note that if you want to write portable code, you can implement your own
"grep" using the "re" module:
</F>
Also, for a wrapper around popen, try commands:

import commands

pattern = raw_input('pattern to search? ')
print commands.getoutput('grep %s *.txt' % pattern)

Pete

Dec 5 '06 #3
pe********@gmail.com wrote:
Also, for a wrapper around popen, try commands:

import commands

pattern = raw_input('pattern to search? ')
print commands.getoutput('grep %s *.txt' % pattern)
that's not quite as portable as the other alternatives, though. "grep"
is at least available for non-Unix platforms, but "commands" requires a
unix shell.

for Python 2.5 and later, you could use:

def getoutput(cmd):
from subprocess import Popen, PIPE, STDOUT
p = Popen(cmd, stdout=PIPE, stderr=STDOUT,
shell=isinstance(cmd, basestring))
return p.communicate()[0]

print getoutput(["grep", pattern, glob.glob("*.txt")])

which, if given a list instead of a string, passes the arguments
right through to the underlying process, without going through the
shell (consider searching for "-" or ";rm" with the original code).

</F>

Dec 5 '06 #4
pe********@gmail.com <pe********@gmail.comwrote:
Also, for a wrapper around popen, try commands:

import commands

pattern = raw_input('pattern to search? ')
print commands.getoutput('grep %s *.txt' % pattern)
What if I entered "; rm -rf * ;" as my pattern?

Don't ever pass user input (from file/web/raw_input) to the shell if
you want to write a secure program!

If you use subprocess then you can use a sequence of args to bypass
the shell rather than a string to be passed to the shell. That will
get over lots of shell escaping problems too. Eg

from subprocess import Popen, PIPE
from glob import glob
pattern = raw_input('pattern to search? ')
files = glob("*.txt")
output = Popen(["grep", pattern] + files, stdout=PIPE).communicate()[0]
print output

You can also use subprocess to read the return code of the command and
its stderr both of which you'll need if you are programming
defensively!

--
Nick Craig-Wood <ni**@craig-wood.com-- http://www.craig-wood.com/nick
Dec 5 '06 #5

Nick Craig-Wood wrote:
>
What if I entered "; rm -rf * ;" as my pattern?
Assuming the script isn't setuid, this would do no more damage than the
user could do directly on the command line. I agree, when dealing with
web applications or setuid programs, direct shell access isn't a good
idea.

Pete

Dec 6 '06 #6
pe********@gmail.com wrote:
Assuming the script isn't setuid, this would do no more damage than the
user could do directly on the command line.
except that when the user is typing things into the command line, he
*knows* that he's typing things into the command line.

</F>

Dec 6 '06 #7
Fredrik Lundh <fr*****@pythonware.comwrote:
pe********@gmail.com wrote:
Assuming the script isn't setuid, this would do no more damage than the
user could do directly on the command line.

except that when the user is typing things into the command line, he
*knows* that he's typing things into the command line.
Aye!

Who is to say that this script won't get re-used innocently in a web
application?

And in this particular example we were talking about typing regular
expressions into the shell, which have many of the same metacharacters
as the shell. So even an innocent use of the above can cause
problems.

Just say no to passing user input (from anywhere at all) via the
shell! That (along with SQL injection attacks which are very similar
in concept) is one of the most common security attacks for scripting
languages like Python when used in a web environment.

--
Nick Craig-Wood <ni**@craig-wood.com-- http://www.craig-wood.com/nick
Dec 6 '06 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Jorgen Grahn | last post by:
I couldn't think of a good solution, and it's hard to Google for... I write python command-line programs under Win2k, and I use the bash shell from Cygwin. I cannot use Cygwin's python package...
0
by: Kyle | last post by:
To any who chose to provide an answer, or even any suggestions to this problem, I thank you greatly in advance. +200 pts. for any valid solutions. I am currently in the process of converting a...
7
by: DB_2 | last post by:
Hello, I was trying to load a comma-separated text file to a DB2 table. I believe I have the syntax rigt for the LOAD command. My first question is, how do you actually run it? It is not a...
2
by: NightHawk | last post by:
Im not a total noob but i don't know the command and the module to go from python to the default shell. (not from interactive mode - $python)
4
by: Anastasios Hatzis | last post by:
I'm looking for a pattern where different client implementations can use the same commands of some fictive tool ("foo") by accessing some kind of API. Actually I have the need for such pattern for...
3
by: George Sakkis | last post by:
I'm trying to figure out why Popen captures the stderr of a specific command when it runs through the shell but not without it. IOW: cmd = if 1: # this captures both stdout and stderr as...
1
by: Tobiah | last post by:
For years now, I've been exiting the shell by typing 'exit\n', being chid by the shell, and then typing ^D. I can't remember a time that I typed the ^D the first time. Call me an idiot if you...
15
by: lixinyi.23 | last post by:
Hi! I'm currently working on a scientific computation software built in python. What I want to implement is a Matlab style command window <-> workspace interaction. For example, you type...
8
by: james.kirin39 | last post by:
Hi everyone, After having used Python on Linux for some time, I now have to do Python coding on Windows. I am big fan of the interactive Python shell to test, eg, regexps. Is there an...
2
by: Kemmylinns12 | last post by:
Blockchain technology has emerged as a transformative force in the business world, offering unprecedented opportunities for innovation and efficiency. While initially associated with cryptocurrencies...
0
by: Naresh1 | last post by:
What is WebLogic Admin Training? WebLogic Admin Training is a specialized program designed to equip individuals with the skills and knowledge required to effectively administer and manage Oracle...
0
by: antdb | last post by:
Ⅰ. Advantage of AntDB: hyper-convergence + streaming processing engine In the overall architecture, a new "hyper-convergence" concept was proposed, which integrated multiple engines and...
0
hi
by: WisdomUfot | last post by:
It's an interesting question you've got about how Gmail hides the HTTP referrer when a link in an email is clicked. While I don't have the specific technical details, Gmail likely implements measures...
0
by: Carina712 | last post by:
Setting background colors for Excel documents can help to improve the visual appeal of the document and make it easier to read and understand. Background colors can be used to highlight important...
0
by: Rahul1995seven | last post by:
Introduction: In the realm of programming languages, Python has emerged as a powerhouse. With its simplicity, versatility, and robustness, Python has gained popularity among beginners and experts...
2
by: Ricardo de Mila | last post by:
Dear people, good afternoon... I have a form in msAccess with lots of controls and a specific routine must be triggered if the mouse_down event happens in any control. Than I need to discover what...
1
by: ezappsrUS | last post by:
Hi, I wonder if someone knows where I am going wrong below. I have a continuous form and two labels where only one would be visible depending on the checkbox being checked or not. Below is the...
0
by: F22F35 | last post by:
I am a newbie to Access (most programming for that matter). I need help in creating an Access database that keeps the history of each user in a database. For example, a user might have lesson 1 sent...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.