如何使用Python执行系统命令方法?老男孩IT教育
Python is a simple programming language, built-in rich libraries, can easily implement powerful features, in the use of Python framework, often need to use Python to execute system commands, some developers are unfamiliar with this, the following is the specific method of operation:
1. Os.system ()
This method directly calls the system () function of standard C, and only runs the systems Command at a sub-terminal, and cannot obtain the information returned by the execution.
>>> Import OS
>>> output = Os.system (' Cat/proc/cpuinfo ')
processor:0
Vendor_id:authenticamd
CPU family:21
... ...
>>> output # doesn ' t capture output
0
2. Os.popen ()
This method executes the command and returns the executed information object, which returns the result through a pipe file.
>>> output = Os.popen (' Cat/proc/cpuinfo ')
>>> output
>>> Print Output.read ()
processor:0
Vendor_id:authenticamd
CPU family:21
... ...
>>>
3. Commands Module
>>> Import Commands
>>> (status, Output) = Commands.getstatusoutput (' Cat/proc/cpuinfo ')
>>> Print Output
processor:0
Vendor_id:authenticamd
CPU family:21
... ...
>>> Print Status
0
Note 1: The return value returned by using this method under Unix-like systems (status) is not equal to the return value after execution of the script or command, because the reason for calling Os.wait () is to understand the implementation of the system wait (). You need the correct return value (status), just move the return value to the right 8-bit operation.
Note 2: subprocess is recommended when the arguments for the command are executed or if the return contains Chinese text.
4. Subprocess Module
This module is a powerful sub-process management module, which is a module of replacing Os.system, os.spawn* and so on.
>>> Import subprocess
>>> subprocess. Popen (["LS", "-L"]) # python2.x doesn ' t capture output
>>> subprocess.run (["LS", "-L"]) # python3.x doesn ' t capture output
>>> Total 68
Drwxrwxr-x 3 XL XL 4096 Feb 8 05:00 com
Drwxr-xr-x 2 XL XL 4096 Jan 02:58 Desktop
Drwxr-xr-x 2 XL XL 4096 Jan 02:58 Documents
Drwxr-xr-x 2 XL XL 4096 Jan 07:44 Downloads
... ...
>>>
The above is the enumeration of Python execution System command method, if you need this aspect of the operation, you can refer to!
How do I use Python to execute system command methods? Old boy It Education