There are two methods to call cmd in the os module, os.popen() and os.system()
os.system(cmd) needs to open a terminal when executing the command command, and cannot save the execution result of the command command.
os.popen(cmd,mode) opens a pipe with the command process. The return value is a file object, which can be read or written (determined by mode, default is'r'). If mode is'r', you can use the return value of this function to call read() to get the execution result of the command command.
os.system()
definition:
def system(*args,**kwargs): # real signature unknown
""" Execute the command in a subshell. """
pass
Simply put, execute the command command in the shell
Example:
( venv) C:\Users\TynamYang python
Python 3.7.0(v3.7.0:1bf9cc5093, Jun 272018,04:06:47)[MSC v.191432bit(Intel)] on win32
Type "help","copyright","credits" or "license"for more information.import os
cmd ='echo "I am tynam"'
os.system(cmd)"I am tynam"
os.popen()
definition:
# Supply 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)
The command command is also executed in the shell, but the returned result is a file object, which can be read and written
**The meaning of the three parameters: **
command — The shell command executed
mode — mode permission, read ('r') or write ('w'), the default is read ('r')
bufsize — If the buffer value is set to 0, no buffering will be performed. If the buffer value is 1, line buffering will be performed when accessing the file. If the buffer value is set to an integer greater than 1, the buffer operation will be performed with the set buffer size. If it is negative, the buffer size is the system default value (default behavior).
**Example: **
import os
cmd ='echo "I am tynam"'
f = os.popen(cmd,'r')
f.read()'"I am tynam"\n'
The above is the whole content of this article, I hope it will be helpful to everyone's study.
Recommended Posts