How to run shell commands within python

F

fileexit

How can I execute shell commands from within python. Specifically, I
am looking for something like the shell "cat". But this also made me
wonder how to execute shell commands anyway, just if i needed to do
that in the future.
 
J

Juho Schultz

fileexit said:
How can I execute shell commands from within python. Specifically, I
am looking for something like the shell "cat". But this also made me
wonder how to execute shell commands anyway, just if i needed to do
that in the future.
You can use os.system() for that.
 
L

limodou

How can I execute shell commands from within python. Specifically, I
am looking for something like the shell "cat". But this also made me
wonder how to execute shell commands anyway, just if i needed to do
that in the future.

You can use os.system() or os.popen(), etc.
 
F

Fredrik Lundh

fileexit said:
thanks... i was to hasty to post this question, i found a good answer
here:
http://groups.google.com/group/comp.lang.python/browse_thread/thread/ffdab847125f81b6

that's an old thread, and Python has grown a few more ways to
deal with shell commands since then. if os.system isn't good en-
ough for you, subprocess is the preferred alternative:

http://www.python.org/doc/lib/module-subprocess.html

(also note that most trivial shell commands are better done in
python. most uses of cat, for example, can be trivially emulated
with one or two lines of python...)

</F>
 
S

Szabolcs Nagy

use subprocess module

from subprocess import call
call(['cmd', 'arg1', 'arg2'], stdin='...', stdout='...')
eg:
call(['ls', '-l'])
 
D

Donn Cave

"Fredrik Lundh said:
(also note that most trivial shell commands are better done in
python. most uses of cat, for example, can be trivially emulated
with one or two lines of python...)

Though the knowledge required to do this may be more trivial
for some of us than others! "cat" probably doesn't have much
going for it that a naive implementation would miss - some
versions will recreate "holes", but most applications will never
miss this. You can replace "mv" with os.rename() if you don't
care that it will fail when the destination is on a different
filesystem. Etc.

Donn Cave, (e-mail address removed)
 
M

Marc 'BlackJack' Rintsch

You can replace "mv" with os.rename() if you don't
care that it will fail when the destination is on a different
filesystem. Etc.

If you care than use `shutil.move()` instead.

Ciao,
Marc 'BlackJack' Rintsch
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,009
Latest member
GidgetGamb

Latest Threads

Top