用Python 执行cmd命令

Python itxz 3年前 (2020-12-19) 375次浏览 已收录 0个评论

我们通常可以使用os模块的命令进行执行cmd

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(执行的<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() 去读取


IT学者 , 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:用Python 执行cmd命令
喜欢 (0)

您必须 登录 才能发表评论!