方法一:os.system
os.system(执行的<a href="http://www.itxz.com/?tag=%e5%91%bd%e4%bb%a4" title="查看更多关于命令的文章" target="_blank">命令</a>) # 源码 def system(*args, **kwargs): # real signature unknown """ Execute the command in a subshell. """ pass
方法二:os.popen(执行的命令)
os.popen(执行的<a href="http://www.itxz.com/?tag=%e5%91%bd%e4%bb%a4" title="查看更多关于命令的文章" target="_blank">命令</a>) # 源码 def popen(<a href="http://www.itxz.com/?tag=cmd" title="查看更多关于cmd的文章" target="_blank">cmd</a>, mode="r", buffering=-1): if not isinstance(<a href="http://www.itxz.com/?tag=cmd" title="查看更多关于cmd的文章" target="_blank">cmd</a>, str): raise TypeError("invalid <a href="http://www.itxz.com/?tag=cmd" title="查看更多关于cmd的文章" target="_blank">cmd</a> type (%s, expected string)" % type(<a href="http://www.itxz.com/?tag=cmd" title="查看更多关于cmd的文章" target="_blank">cmd</a>)) if mode not in ("r", "w"): raise ValueError("invalid mode %r" % mode) if buffering == 0 or buffering is None: raise ValueError("popen() does not support unbuffered streams") import subprocess, io if mode == "r": proc = subprocess.Popen(<a href="http://www.itxz.com/?tag=cmd" title="查看更多关于cmd的文章" target="_blank">cmd</a>, shell=True, stdout=subprocess.PIPE, bufsize=buffering) return _wrap_close(io.TextIOWrapper(proc.stdout), proc) else: proc = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, bufsize=buffering) return _wrap_close(io.TextIOWrapper(proc.stdin), proc)
两者区别
system只把能输入的内容给返回回来了,其中代码 0 表示执行成功。但是我们没有办法获取输出的信息内容
popen可以获取输出的信息内容,它是一个对象,可以通过 .read() 去读取