python执行shell命令
import os
import subprocess
def run_cmd_system(command):
try:
print(f"通过system运行run command: {command}")
os.system(command)
except Exception as e:
print(f"命令运行失败!{e}")
raise e
def run_cmd_popen(command):
try:
print(f"通过popen运行run command: {command}")
os.popen(command)
print("os.popen什么都没打印出来")
print(os.popen(command))
print(os.popen(command).readlines())
print(type(os.popen(command).readlines()))
except Exception as e:
print(f"命令运行失败!{e}")
raise e
def run_cmd_subprocess(command):
try:
print(f"通过subprocess运行run command: {command}")
res = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
res.wait()
result = res.stdout.readlines()
print(type(result))
print(result)
except subprocess.CalledProcessError as e:
print(f"命令运行失败!{e}")
raise e
return result
if __name__ == "__main__":
run_cmd_subprocess("ls")
run_cmd_system("ls")
run_cmd_popen("ls")
结果
通过subprocess运行run command: ls
<class 'list'>
[b'__init__.py\n', b'__pycache__\n', b'commandrun.py\n', b'fastapiOne.py\n', b'fastapiTwo.py\n', b'logged.py\n', b'maoli.py\n']
通过system运行run command: ls
__init__.py
__pycache__
commandrun.py
fastapiOne.py
fastapiTwo.py
logged.py
maoli.py
通过popen运行run command: ls
os.popen什么都没打印出来
<os._wrap_close object at 0x7fa3fd242820>
['__init__.py\n', '__pycache__\n', 'commandrun.py\n', 'fastapiOne.py\n', 'fastapiTwo.py\n', 'logged.py\n', 'maoli.py\n']
<class 'list'>
|