Python calling windows command

Python Run Shell Command On Windows

Welcome to Python Run Shell Command On Windows tutorial. In this tutorial, you will learn, how to run shell command in python. So let’s move forward.

Python Run Shell Command On Windows

What is Shell ?

  • In computer science shell is generally seen as a piece of software that provides an interface for a user to some other software or the operating system.
  • So the shell can be an interface between the operating system and the services of the kernel of this operating system

Python Modules For Running Shell command

Python provides lots of modules for executing different operations related to operating system.

Generally there are two important modules which are used to run shell command in python.

Python Run Shell Command Using Subprocess module

The subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. This module intends to replace several older modules and functions:

The subprocess module allows users to communicate from their Python script to a terminal like bash or cmd.exe.

Now we will see different functions of subprocess module.

subprocess.call()

call() method create a separate process and run provided command in this process.

Write the following code to implement call() method of subprocess module.

Источник

Execute a Command Prompt Command from Python

Data to Fish

Need to execute a Command Prompt command from Python?

If so, depending on your needs, you may use either of the two methods below to a execute a Command Prompt command from Python:

(1) CMD /K – execute a command and then remain:

import os os.system('cmd /k "Your Command Prompt Command"')

(2) CMD /C – execute a command and then terminate:

import os os.system('cmd /c "Your Command Prompt Command"')

Still not sure how to apply the above methods in Python?

Читайте также:  Html href window size

Let’s then review few examples to better understand how to execute a Command Prompt command from Python.

Methods to Execute a Command Prompt Command from Python

Method 1 (CMD /K): Execute a command and then remain

To see how to apply the first method in practice, let’s review a simple example where we’ll execute a simple command in Python to:

  • Display the current date in the Command Prompt
  • The Command Prompt will remain opened following the execution of the command

You may then apply the following code in Python to achieve the above goals:

import os os.system('cmd /k "date"')

Once you run the code in Python, you’ll get the date in the command prompt:

Now what if you want to execute multiple command prompt commands from Python?

If that’s the case, you can insert the ‘&’ symbol (or other symbols, such as ‘&&’ for instance) in between the commands.

For example, what if you want to display all the characters in the command prompt in green and display the current date?

You can then use the following syntax in Python:

import os os.system('cmd /k "color a & date"')

You’ll now see the current date displayed in green:

Note that for more complex commands, you may find it useful to run a batch file from Python.

Method 2 (CMD /C): Execute a command and then terminate

For this method, you can execute the same commands as reviewed under the first method, only this time the Command Prompt will be closed following the execution of the commands.

For example, you may apply the following code in Python to change the color of all characters to green:

import os os.system('cmd /c "color a"')

In this case, the command will still get executed, but you may not be able to see it on your monitor.

In general, you can get a useful legend with further information by typing the command below in the Command Prompt:

Читайте также:  Время создания сессии php

Источник

Системные команды с помощью 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 . И возвращает нам код выхода или статус.

Читайте также:  Line functions in java

В приведенном ниже фрагменте кода мы пытаемся установить 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()

Источник

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