Python system command line

Python System Command: How to Execute Shell Commands in Python?

System Commands In Python

Today in this tutorial, we are going to discuss how we can execute shell commands using Python system command.

So let’s get started with some basics of Python system command.

What is Python System Command?

We may need to integrate features for carrying out some system administration tasks in Python. These include finding files, running some shell commands, doing some advanced file handling, etc. And to do so, we need some way to interface between the system and the python interpreter.

Executing command lines using Python can be easily done using some system methods from the os module .

But with the introduction of the subprocess module(intending to replace some older modules), accessing command line has been a lot more easier to use. As well as to manipulate the output and avoid some limitations of the traditional methods.

Executing Shell Commands in Python

Now that we got to know about the System Commands in Python. Let us take a look into how we can implement the same.

1. Using os.system() Method

As stated earlier, executing shell commands in Python can be easily done using some methods of the os module. Here, we are going to use the widely used os.system() method.

Читайте также:  Tensorflow python установка pip

This function is implemented using the C system() function, and hence has the same limitations.

The method takes the system command as string in input and returns the exit code back.

In the example below, we try to check our system Python version using command line in 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

Here, res stores the returned value (exit code=0 for success). It is clear from the output, that the command is executed successfully and we get our Python version as expected.

2. Using the subprocess Module

The subprocess module comes with various useful methods or functions to spawn new processes, connect to their input/output/error pipes, and obtain their return codes.

In this tutorial, we are considering the call() and check_output() methods as they are easy to use and reliable. But for more info you can always refer to the official documentation.

2.1. The call() Method

Now getting to the subprocess.call() method.

The call() method takes in command line arguments passed as a list of strings or with the shell argument set to True . And returns back us the exit code or status.

In the below code snippet, we try to install pandas using PIP from shell.

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

As we can see, the command is executed successfully with return value zero .

2.2. The check_output() Method

The above mentioned methods execute the shell command passed successfully but don’t give the user the freedom to manipulate the way we get the output. For doing that, the subprocess’s check_output() method has to come into the picture.

The method executes the passed command but instead of returning the exit status, this time it returns a bytes object.

Take a closer look at the example below where we try to install the pymysql module again(already installed).

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)

Here similar to the previous cases, res holds the returned object by the check_output() method. We can see type(res) confirms that the object is of bytes type.

After that, we print the decoded string and see that the command was successfully executed.

Conclusion

So, today we learned how we can execute system commands using Python system command (os.system()) and the subprocess module. We have considered some more python related commands here, but it is worth noting that the methods are not limited to these.

We recommend trying out other commands using the above methods on your own to get a better understanding.

For any further questions, feel free to comment below.

References

Источник

Системные команды с помощью 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() поскольку они просты в использовании и надежны. Но для получения дополнительной информации вы всегда можете обратиться к официальной документации.

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()

Источник

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