How to run external commands on python:
Python support running external commands, such as linux terminal commands, version control terminal commands from inside python script. Earlier python had a module called ‘commands’ for this purpose. But now it is obsolete and it has more powerful and featured module called ‘subprocess’. Lets meet those two modules one by one.
Here is an example with commands module. This will run the terminal command ‘ls’ to list the files and folders in my home directory. This will return output to ‘output’ variable and success/failure status to ‘status’ variable’. Try this command in your terminal and identify how the output look likes!.
Since Python 2.4 all process management functionalities are packaged under subprocess module which provide one class called Popen which is all you need to use. The subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. This module intends to replace several other, older modules and functions,
subprocess module provides two ways to run external commands, ‘call’ and ‘Popen’. Obviously there are some difference between using these two. At first let see some examples for both.
Using call() to execute terminal commands:
You can run ‘ls’ command (linux terminal command to show list of files and folders inside current directory) like this.
from subprocess import call
When we have multiple arguements we can use list inside call.
call(["ls", "-l"], shell=True)
Using Popen() to execute terminal commands:
from subprocess import Popen
Both call and Popen seems to be same but Popen provides more flexibility to the programmer. You can read some difference from here.
Lets run some mercurial commands:
With the knowledge above lets see a small program run some mercurial commands using python program. Later you can modify this program to automate your bitbucket upload.
subprocess.Popen([“hg”, “add”], cwd=”/home/jinesh/testing”)
username = raw_input('Enter Username of bitbucket')
passphrase = raw_input('Enter a passphrase')
call("hg push", shell=True)
repo = raw_input("Enter your repo name")
call("hg clone "+repo, shell=True)
Note: Please try to read more about these commands from python documentation. I wrote this with an introduction purpose only.