Для выполнения консольных команд с помощью Python вы можете использовать различные методы в зависимости от ваших требований. Вот несколько распространенных подходов:
Метод 1: использование модуля subprocess
import subprocess
# Execute a command and capture the output
result = subprocess.run(["ls", "-l"], capture_output=True, text=True)
print(result.stdout)
# Execute a command and get the return code
subprocess.run(["mkdir", "new_directory"])
Метод 2: использование модуля os
import os
# Execute a command
os.system("ls -l")
# Execute a command and get the output
output = os.popen("ls -l").read()
print(output)
Метод 3: использование модуля sh
import sh
# Execute a command and capture the output
output = sh.ls("-l")
print(output)
# Execute a command and get the output as a list
files = sh.ls().split()
print(files)
Метод 4. Использование модуля pexpect
(для интерактивных команд)
import pexpect
# Spawn a child process and interact with it
child = pexpect.spawn("ftp ftp.example.com")
child.expect("Name .*:")
child.sendline("myusername")
child.expect("Password:")
child.sendline("mypassword")
child.expect("ftp>")
child.sendline("ls")
child.expect("ftp>")
print(child.before.decode())
Это всего лишь несколько примеров выполнения консольных команд с помощью Python. Выбор наилучшего метода зависит от конкретных требований вашего проекта.