Windows system calls python

Системные команды с помощью 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()

Источник

Call system command python if linux or windows

For others error codes: on Linux on Windows Solution 2: returns a 16 bit number, which first 8 bits from left(lsb) talks about signal used by os to close the command, Next 8 bits talks about return code of command. Solution: The portable code should use a list argument (drop ) or it should pass the command as a string if is required. Don’t use relative paths such as : either pass the absolute path (including the file extension) or rely on envvar and use something like: .

Python system call that works on windows and linux

The portable code should use a list argument (drop shell=True ) or it should pass the command as a string if shell=True is required.

Don’t use relative paths such as ../ : either pass the absolute path (including the file extension) or rely on PATH envvar and use something like: program = ‘engine’ .

Python execute windows cmd functions, dir is not a file, it is an internal command, so the shell keyword must be set to True. subprocess.call([«dir»], shell=True).

Running Shell Commands using Python (Detailed Explanation)

In this video, learn how to run shell commands using Python. This is useful when your python
Duration: 29:42

How do I detect different OS system [duplicate]

os.name would return nt if your system is Windows, and posix if POSIX, so you can do it like this

import os if os.name == 'nt': os.system('cls') else: os.system('clear') 

How to execute commands from a command-line program one after, I tried subprocess.run function putting the name of the exe followed by the commands I want to execute inside the brackets and then these

Python execute windows cmd functions

dir is not a file, it is an internal command, so the shell keyword must be set to True.

subprocess.call(["dir"], shell=True) 
import os os.system("windows command") 

Almost everyone’s answers are right but it seems I can do what I need using os.popen — varStr = os.popen(‘dir /b *.py’).read()

How do I detect different OS system, os.name would return nt if your system is Windows, and posix if POSIX, so you can do it like this import os if os.name == ‘nt’:

What is the return value of os.system() in Python?

The return value of os.system is OS-dependant.

On Unix, the return value is a 16-bit number that contains two different pieces of information. From the documentation:

a 16-bit number, whose low byte is the signal number that killed the process, and whose high byte is the exit status (if the signal number is zero)

So if the signal number (low byte) is 0, it would, in theory, be safe to shift the result by 8 bits ( result >> 8 ) to get the error code. The function os.WEXITSTATUS does exactly this. If the error code is 0, that usually means that the process exited without errors.

On Windows, the documentation specifies that the return value of os.system is shell-dependant. If the shell is cmd.exe (the default one), the value is the return code of the process. Again, 0 would mean that there weren’t errors.

os.system(‘command’) returns a 16 bit number, which first 8 bits from left(lsb) talks about signal used by os to close the command, Next 8 bits talks about return code of command.

00000000 00000000 exit code signal num 

Example 1 — command exit with code 1

os.system('command') #it returns 256 256 in 16 bits - 00000001 00000000 Exit code is 00000001 which means 1 

Example 2 — command exit with code 3

os.system('command') # it returns 768 768 in 16 bits - 00000011 00000000 Exit code is 00000011 which means 3 

Now try with signal — Example 3 — Write a program which sleep for long time use it as command in os.system() and then kill it by kill -15 or kill -9

os.system('command') #it returns signal num by which it is killed 15 in bits - 00000000 00001111 Signal num is 00001111 which means 15 

You can have a python program as command = ‘python command.py’

import sys sys.exit(n) # here n would be exit code 

In case of c or c++ program you can use return from main() or exit(n) from any function #

Note — This is applicable on unix

On Unix, the return value is the exit status of the process encoded in the format specified for wait(). Note that POSIX does not specify the meaning of the return value of the C system() function, so the return value of the Python function is system-dependent.

os.wait()

Wait for completion of a child process, and return a tuple containing its pid and exit status indication: a 16-bit number, whose low byte is the signal number that killed the process, and whose high byte is the exit status (if the signal number is zero); the high bit of the low byte is set if a core file was produced.

return_value = os.popen('ls').read() 

instead. os.system only returns the error value.

The os.popen is a neater wrapper for subprocess.Popen function as is seen within the python source code.

Python system call that works on windows and linux, The portable code should use a list argument (drop shell=True ) or it should pass the command as a string if shell=True is required.

Источник

Читайте также:  How to reverse dict python
Оцените статью