1

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.

4 Answers 4

2

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')
Sign up to request clarification or add additional context in comments.

2 Comments

looks great. how would i store the result into a database?
To store in a database, go through the django tutorial: docs.djangoproject.com/en/dev/intro/tutorial01
2

reece's answer almost works, but you need to append Popen with .communicate()

so it would be:

from subprocess import Popen, PIPE
stdout, stderr = Popen(['echo', 'Hello World!'], shell=False, stdout=PIPE).communicate()

Or in Python 2.7 you can use:

from subprocess import check_output
stdout = check_output(['echo', 'Hello World!'], shell=False)

See subprocess: http://docs.python.org/library/subprocess.html

Comments

1

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.

Comments

0

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.