编程语言
首页 > 编程语言> > Python - 执行cmd命令

Python - 执行cmd命令

作者:互联网

python操作cmd

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

 

方法一:os.system

os.system(执行的命令)
# 源码
def system(*args, **kwargs): # real signature unknown
    """ Execute the command in a subshell. """
    pass

 

方法二:os.popen(执行的命令)

os.popen(执行的命令)

# 源码
def popen(cmd, mode="r", buffering=-1):
    if not isinstance(cmd, str):
        raise TypeError("invalid cmd type (%s, expected string)" % type(cmd))
    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(cmd,
                                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)

 

两者区别

 

标签:Python,cmd,popen,subprocess,命令,mode,buffering,proc
来源: https://blog.51cto.com/u_12020737/2838286