Running system commands from within Python scripts
import os
os.system('your command goes here')
The commands you can pass are operating system specific. For example, to clear the console screen in Windows, it’ll be
os.system('cls')
and to clear the console screen in Mac it’ll be
os.system('clear')
Both are OS specific commands for the same purpose.
You can read more about the os library in the Python documentation for os v15.1 in Python 2 and v16.1 in Python 3.
Basic Examples
Clear the screen
Win
os.system('cls')
Mac
os.system('clear')
Create a Directory
Win
os.system('mkdir dirNmae')
Mac
os.system('mkdir dirName')
Open a file (for example: config file after install)
Win
os.system('edit fileName')
Mac
os.system('nano config.php')
Deleting files (for example: temporary install files)
Win
os.system('del fileName')
Mac
os.system('rm fileName')
Download and Extract a tarball in a new folder and then move to the extracted folder (for exaple: download and install a software/script)
Mac
os.system('wget http://download/link/downloadName.tar.gz && mkdir folderName && tar zxvf downloadName.tar.gz --directory folderName && cd folderName')
Where:
- http://download/link/downloadName.tar.gz = direct link for the file download
- downloadName = name of the downloaded file
- folderName = the folder where ou are going to extract the files