Using system commands in python

How do you execute a system command in Python?

In this article we will learn to execute a system command in Python Programming Language.

Table Of Contents

Introduction

Today we will be discussing about different methods using which we can execute system/shell commands in Python. This can be useful to automate things which requires a communication with the system. Mainly there are two modules that can be used to execute a system command in python.

So here we will learn about different modules and methods in Python Programming language through which you can execute system commands. Also we will demonstrate you by creating a directory with the mkdir command in the system.

mkdir is a command used to create folder/directory in OS like windows, LINUX,UNIX.

Execute a system command in Python using the OS Module

We can use OS module of Python programming language, to execute system command in Python. OS module comes bundled with Python. It provides us with many functions, which can be used to interact with the operating system. It has many useful functions which provide direct manipulation with files and folders. But here we will be using os.system() with some system commands. For example,

Frequently Asked:

os.system: This function creates a sub-shell inside the python shell(where the python program runs), and executes the system commands. If returned any string by the sub-shell(where the system commands are running), then it returns the string back to Python interpreter and hence visible to user. This way this module can be used for proper input-output communication with the system command. Whatever is passed in the os.system() as a string, is used as a command in system command. Like if you pass “dir” inside the os.system(), it will work as the same as when you type dir in system command/command prompt.

import os # echo is used to print string in cmd. os.system("echo Hello, I am Python. I have created a directory for you.") # mkdir creates a new folder/directory in the cmd. os.system("mkdir python") # dir prints the directories/folders available in the folder. os.system("dir")
Hello, I am Python. I have created a directory for you. 12:49 PM 940 code.py 12:49 PM python 1 File(s) 940 bytes 3 Dir(s) 202,821,668,864 bytes free

In the above code and output, you can see how os module is being used to execute system command in python. The mkdir and dir commands has been used to create a new folder named python in the working directory, and list all the available directories respectively.

Читайте также:  Browser url in javascript

Execute a system command in Python using the Subprocess Module

Next we can use the subprocess module of Python Programming Language to execute a system command in Python. This module comes bundled with python. This module is the mostly used and recommended executing system commands. This module is an alternative of OS module because some very useful features like:

  • Connects to input/output/error pipes and obtains their return codes.
  • Allows to spawn new process.

This module offers a lot more, for more detailed study go to the Python SubProcess Module DOCS

import subprocess # creating a folder at current path using mkdir and subprocess.run() function file = subprocess.run("mkdir subprocess",shell=True) # returncode prints the status of the process subprocess.run(), 0 means that the program ran successfully. print(file.returncode) # shell=True because dir command is built into the shell. subprocess.run("dir",shell= True)
0 575 script.py subprocess

So, In the code and output above you can see subprocess module has been used to create a new folder in the system using mkdir and subprocess.run() function. Also we have passed shell=True has been passed. It has done to prevent us from getting an error, because the dir command is built into the shell.

Summary

So, In this Python tutorial article we learned to execute a system command in Python. We learned about two most popular and most used and useful modules which are widely used to execute system command in Python. First is OS module which provides some useful functions like os.getcwd(), os.fdopen(fd, args, *kwargs), os.pipe(), os.system, os.run, etc. which are used for interaction with OS and file maipulation. Visit Official Python Docs. Also we used Subprocess module which is the most recommended and mostly used to execute a system command in Python, it provides with vast of functions/methods through which we can do file manipulation, os communication and a lot more with the help of function/methods like: subprocess.run(), subprocess.Popen(), Popen.poll(), subprocess.PIPE, etc. Visit the Official Python Docs.

Читайте также:  Определение максимального числа java

Make sure to read/write the code samples from this article, to have a better understanding of the solutions. Thanks.

Источник

Системные команды с помощью Python (os.system())

Возможно, нам потребуется интегрировать функции для выполнения некоторых задач системного администрирования в Python. К ним относятся поиск файлов, выполнение некоторых команд оболочки, выполнение некоторой расширенной обработки файлов и т. д. И для этого нам нужен какой-то способ взаимодействия между системой и интерпретатором Python.

Выполнение командных строк с помощью Python можно легко выполнить с помощью некоторых системных методов из os module .

Но с появлением модуля subprocess (с намерением заменить некоторые старые модули) доступ к командной строке стал намного проще в использовании. А также для управления выводом и избежания некоторых ограничений традиционных методов.

System Commands In Python

Выполнение команд оболочки в Python

Теперь, когда мы узнали о системных командах в Python. Давайте посмотрим, как мы можем реализовать то же самое.

1. Использование метода os.system()

Как указывалось ранее, выполнение команд оболочки в Python можно легко выполнить с помощью некоторых методов модуля os . Здесь мы собираемся использовать широко используемый os.system() .

Эта функция реализована с использованием функции C system() и, следовательно, имеет те же ограничения.

Метод принимает системную команду как строку на входе и возвращает код вывода.

В приведенном ниже примере мы пытаемся проверить версию Python в нашей системе с помощью командной строки.

import os command = "python --version" #command to be executed res = os.system(command) #the method returns the exit status print("Returned Value: ", res)
Python 3.7.4 Returned Value: 0

Здесь res сохраняет возвращенное значение (код выхода = 0 для успеха). Из выходных данных видно, что команда выполнена успешно, и мы получили нашу версию Python, как и ожидалось.

2. Использование модуля подпроцесса

Модуль subprocess поставляется с различными полезными методами или функциями для создания новых процессов, подключения к их каналам ввода / вывода / ошибок и получения их кодов возврата.

В этом руководстве мы рассматриваем методы call() и check_output() поскольку они просты в использовании и надежны. Но для получения дополнительной информации вы всегда можете обратиться к официальной документации.

Читайте также:  Java util properties source

2.1. Метод call()

Теперь перейдем к методу subprocess.call() .

Метод call() принимает аргументы командной строки, переданные в виде списка строк или с аргументом оболочки, установленным в True . И возвращает нам код выхода или статус.

В приведенном ниже фрагменте кода мы пытаемся установить pandas с помощью PIP из оболочки.

import subprocess command = "pip install pandas" #command to be executed res = subprocess.call(command, shell = True) #the method returns the exit code print("Returned Value: ", res)
Collecting pandas Downloading pandas-1.0.3-cp37-cp37m-win32.whl (7.5 MB) Requirement already satisfied: pytz>=2017.2 in c:\users\sneha\appdata\local\programs\python\python37-32\lib\site-packages (from pandas) (2019.3) Requirement already satisfied: numpy>=1.13.3 in c:\users\sneha\appdata\local\programs\python\python37-32\lib\site-packages (from pandas) (1.18.1) Requirement already satisfied: python-dateutil>=2.6.1 in c:\users\sneha\appdata\local\programs\python\python37-32\lib\site-packages (from pandas) (2.8.1) Requirement already satisfied: six>=1.5 in c:\users\sneha\appdata\local\programs\python\python37-32\lib\site-packages (from python-dateutil>=2.6.1->pandas) (1.14.0) Installing collected packages: pandas Successfully installed pandas-1.0.3 Returned Value: 0

Как видим, команда выполнена успешно с zero возвращаемым значением.

2.2. Метод check_output()

Вышеупомянутые методы выполняют успешно переданную команду оболочки, но не дают пользователю свободы манипулировать способом получения вывода. Для этого на check_output() должен check_output() метод подпроцесса check_output() .

Метод выполняет переданную команду, но вместо возврата статуса выхода на этот раз возвращает bytes объект.

Присмотритесь к приведенному ниже примеру, где мы снова пытаемся установить модуль pymysql (уже установленный).

import subprocess command = "pip install pymysql" #command to be executed res = subprocess.check_output(command) #system command print("Return type: ", type(res)) #type of the value returned print("Decoded string: ", res.decode("utf-8")) #decoded result
Return type: Decoded string: Requirement already satisfied: pymysql in c:\users\sneha\appdata\local\programs\python\python37-32\lib\site-packages (0.9.3)

Здесь, как и в предыдущих случаях, res хранит объект, возвращаемый методом check_output() . Мы видим, что type(res) подтверждает, что объект имеет bytes тип.

После этого печатаем декодированную строку и видим, что команда успешно выполнена.

Вывод

Итак, сегодня мы узнали, как мы можем выполнять системные команды с помощью системной команды Python (os.system()) и модуля подпроцесса. Мы рассмотрели здесь еще несколько команд, связанных с Python, но стоит отметить, что методы этим не ограничиваются.

Мы рекомендуем попробовать другие команды, используя описанные выше методы, чтобы лучше понять.

Если у вас возникнут дополнительные вопросы, оставляйте комментарии ниже.

Ссылки

  • Документация подпроцесса Python
  • Документация по ОС Python,
  • Системная команда Python — os.system(), subprocess.call() — статья о Journal Dev
  • Предыдущая Генерация случайных целых чисел с помощью Python randint()
  • следующий Учебник Python MySQL — Полное руководство

Генерация случайных целых чисел с помощью Python randint()

Источник

Оцените статью