Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run commands on shell through python [duplicate]

Possible Duplicate:
Calling an external command in Python

I want to run commands in another directory using python.

What are the various ways used for this and which is the most efficient one?

What I want to do is as follows,

cd dir1
execute some commands
return 
cd dir2
execute some commands
like image 626
mrutyunjay Avatar asked Jan 22 '13 11:01

mrutyunjay


People also ask

Can I use Python to execute shell commands?

Python allows you to execute shell commands, which you can use to start other programs or better manage shell scripts that you use for automation. Depending on our use case, we can use os. system() , subprocess. run() or subprocess.

How do you execute a shell command in Python and get output?

Get output from shell command using subprocess A better way to get the output from executing a linux command in Python is to use Python module “subprocess”. Here is an example of using “subprocess” to count the number of lines in a file using “wc -l” linux command.

How do I run a shell command in Python using subprocess?

Python Subprocess Run Function The subprocess. run() function was added in Python 3.5 and it is recommended to use the run() function to execute the shell commands in the python program. The args argument in the subprocess. run() function takes the shell command and returns an object of CompletedProcess in Python.


2 Answers

Naturally if you only want to run a (simple) command on the shell via python, you do it via the system function of the os module. For instance:

import os
os.system('touch myfile')

If you would want something more sophisticated that allows for even greater control over the execution of the command, go ahead and use the subprocess module that others here have suggested.

For further information, follow these links:

  • Python official documentation on os.system()
  • Python official documentation on the subprocess module
like image 109
NlightNFotis Avatar answered Sep 23 '22 18:09

NlightNFotis


If you want more control over the called shell command (i.e. access to stdin and/or stdout pipes or starting it asynchronously), you can use the subprocessmodule:

import subprocess

p = subprocess.Popen('ls -al', shell=True, stdout=subprocess.PIPE)
stdout, stderr = p.communicate()

See also subprocess module documentation.

like image 24
helmbert Avatar answered Sep 24 '22 18:09

helmbert