views:

78

answers:

4

Hi all, I have a question regarding the use of Python.

How do i run a command line command using Python? And after running the command, how do i save the returned values?

For example:

user@home:~$: ls -l
drwxr-xr-x 3 root root 4096 ..[etc] home
-rw-r--r-- 1 user user 357 ..[etc] examples.doc

So what i intend to do, is to run the command ls -l and than save the response into a database using Python.

I intend to implement the above example in Django.

May I know if it is possible? What kind of commands I cannot execute?

How do i implement it?

Any links, tutorials, advice is more than welcome!

Best Regards.

A: 

Have a look at os.system function. With that call, you will be able to execute any command like:

import os
os.system( 'ls -l > file.txt' )

http://docs.python.org/library/os.html#os.system

djondal
reece answer seems to be the rigth way to go. I'll vote for his answer because his solution has a direct access to stdout and stderr
djondal
+2  A: 

You need to use subprocess -- http://docs.python.org/library/subprocess.html and http://docs.python.org/library/subprocess.html:

from subprocess import Popen, PIPE
stdout, stderr = Popen(['echo', 'Hello World!'], shell=False, stdout=PIPE)
print stdout.split('\n')
reece
looks great. how would i store the result into a database?
DjangoRocks
To store in a database, go through the django tutorial: http://docs.djangoproject.com/en/dev/intro/tutorial01/
twneale
A: 

Check out the standard subprocess model - it has an example for doing just that:

http://docs.python.org/library/subprocess.html#replacing-shell-pipeline

smichak
A: 

You're not actually asking the right question here. As others have said, os.system or subprocess.Popen are the answers to the question 'how can I run a shell command in Python.

But that's not the question you are really asking. What you actually want to know is, how can I get the files in a directory? And the answer to that question is to use os.listdir(). See the documentation.

Daniel Roseman
yes spot on. thanks!
DjangoRocks