473,385 Members | 1,569 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 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 2686
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...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?

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.