Execute the cmd command with Python
- 2021-08-28 20:34:43
- OfStack
We can usually use the commands of the os module to execute cmd
Method 1: os. system
os.system( Executed commands )
# Source code
def system(*args, **kwargs): # real signature unknown
""" Execute the command in a subshell. """
pass
Method 2: os. popen (command executed)
os.popen( Executed commands )
# Source code
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)
Difference between the two
system returns only what can be entered, where code 0 indicates successful execution. But we have no way to get the output information content
popen can get the output information content, which is an object and can be read through. read ()
The above is the Python execution cmd command details, more about python execution cmd command information please pay attention to other related articles on this site!