Recently in the framework of the test to find that the Python Execution System command is not familiar with, so think about the following, this article is mainly about the implementation of the system command in Python method, the need for friends can reference, let's take a look at it.
Objective
Python is often referred to as "glue language" because it can easily manipulate other programs and easily wrap libraries written in other languages. In a Python/wxpython environment, execute an external command or a method that launches another program in a Python program.
This article will detail about how to execute system commands in Python, and let's talk about this in detail.
(1) Os.system ()
This method calls the standard C system() function directly, running the system command only at a sub-terminal, and not getting the information returned by the execution.
>>> import os >>> output = Os.system (' cat/proc/cpuinfo ') processor:0 VENDOR_ID:AUTHENTICAMD CPU Fam ily: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 <open file ' Cat/proc/cpuinfo ', mode ' R ' at 0x7 ff52d831540> >>> Print output.read () processor:0 VENDOR_ID:AUTHENTICAMD CPU family:21 ... >>&g T;<span style= "FONT-SIZE:14PX;" >
(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
The module is a powerful sub-process management module, which is os.system os.spawn* a module of substitution, and other methods.
>>> Import subprocess >>> subprocess. Popen (["LS", "-l"]) <strong> # python2.x</strong> doesn ' t capture output >>> subprocess.run (["LS", "-L"]) <strong># python3.x</strong> doesn ' t capture output <subprocess. Popen object at 0x7ff52d7ee490> >>> Total drwxrwxr-x 3 XL XL 4096 Feb 8 05:00 com drwxr-xr-x 2 XL xl 4096 J An 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 ... >>>