目录
方案一:os.syetem()
每一条system函数执行时,其会创建一个子进程在系统上执行命令行,子进程的执行结果无法影响主进程;
import os
result = os.system('python -V')
print(result) # 0
# 为保证system执行多条命令可以成功,多条命令需要在同一个子进程中运行;如:
os.system('cd /usr/local')
os.system('mkdir aaa.txt')
#替换为
os.system('cd /usr/local; mkdir aaa.txt')
返回:成功会返回0
缺点:中文会乱码
方案二:os.popen()
调用方式是通过管道的方式来实现,函数返回一个file对象
import os
result = os.popen('python -V')
print(result) # <os._wrap_close object at 0x0000018B56FFBF98>
print(result.read()) # Python 3.6.3 :: Anaconda, Inc.
返回:返回值是文件对象fd
方案三:subprocess.Popen()
启动一个新的进程并与之通信,最常用是定义类Popen,使用Popen可以创建进程,并与进程进行复杂的交互。
import subprocess
result = subprocess.Popen("python -V", stdout=subprocess.PIPE)
print(result) # <subprocess.Popen object at 0x000002B59DAA0908>
result = result.stdout.read().decode('utf-8')
print(result) # Python 3.6.4