【进阶14】【自学笔记】Python运行cmd命令的几种方式

发布时间 2023-04-20 22:09:22作者: 橙子测试笔记

1、使用os.system()函数

import os

# 运行cmd命令
os.system('dir') 

2、使用subprocess模块

import subprocess

# 运行cmd命令
subprocess.run(['dir'], shell=True)

3、使用os.popen()函数

import os

# 运行cmd命令
result = os.popen('dir')
print(result.read())

4、使用commands模块(Python 2.x版本中可用)

import commands

# 运行cmd命令
status, output = commands.getstatusoutput('dir')
print(output)

上述代码中,我们分别使用了os.system()、subprocess模块、os.popen()和commands模块等方式来执行cmd命令。其中,os.system()函数和subprocess模块较为常用,os.popen()和commands模块已经逐渐被废弃,推荐使用subprocess模块来代替。每个函数或模块的具体作用请参考官方文档。