How to call an external command from Python
In this tutorial post, we are going to learn how to call an external command from Python. External commands are those command which we run on our command prompt in windows.
Examples of External commands are dir, cd, md, ipconfig, etc.
Also read: Python Command Line Arguments
Before going with the programming part, first, we will learn the use of some command of MS-DOS.
dir Display list of contents of current directory cd Change directory or display current directory path md Creates a directory notepad Run the Windows Notepad text editor ipconfig Displays internet configuration, including IP address
For better understanding, we will use all these commands in our program and learn how to call external commands from python.
Calling external commands from Python
For calling external commands we will import a module subprocess.
With the help of the subprocess module, we will call the external commands.
import subprocess subprocess.call('cd',shell=True)
Display the file path. C:\Users\VIMAL\PycharmProjects\Vimal_Pandey\Pyth\Codespeedy
According to Python documentation If the shell is True, the specified command will be executed through the shell.
The shell work the same as command prompt of windows or shell of UNIX.
To open notepad we will use notepad command in our program.
For making directory(folder ) we use “md” command in our windows command prompt. The same command we will use in Python.
import subprocess subprocess.call("md codespeedy",shell=True)
Folder with name codespeedy is created in current working directory.
There is also the method of calling an external command in python beside the subprocess module.
import os cmd = 'ipconfig' os.system(cmd)
Shows Windows Ipconfiguration and wireless connectivity details.
I hope you understood how to call an external command from Python. Comment your doubts related to this post. If you have any other query please comment below.