Notes

Running system commands from within Python scripts

Edit on GitHub

Python
1import os
2os.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

1os.system('cls')

and to clear the console screen in Mac it’ll be

1os.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

1os.system('cls')

Mac

1os.system('clear')

Create a Directory

Win

1os.system('mkdir dirNmae')

Mac

1os.system('mkdir dirName')

Open a file (for example: config file after install)

Win

1os.system('edit fileName')

Mac

1os.system('nano config.php')

Deleting files (for example: temporary install files)

Win

1os.system('del fileName')

Mac

1os.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

1os.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