温馨提示×

python如何调用cmd命令行

小亿
115
2024-12-05 06:20:23
栏目: 编程语言
Python开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在Python中,你可以使用subprocess模块来调用命令行

import subprocess

# 要执行的命令行命令,例如:dir(Windows)或ls(Linux/macOS)
command = "dir"  # 或者 "ls" 如果你在Linux/macOS上运行此代码

# 使用subprocess.run()执行命令
result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, shell=True)

# 打印执行结果
print("命令行输出:")
print(result.stdout)
print("错误输出:")
print(result.stderr)
print("返回码:")
print(result.returncode)

注意:在使用shell=True时,请确保你信任要执行的命令,因为它可能会导致安全漏洞。避免在不受信任的输入上使用shell=True

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:python如何执行cmd命令行

0