Detailed examples of how to execute system commands in Python.
Preface
Python is often called the "glue language" because it can easily operate other programs and easily wrap libraries written in other languages. In the Python/wxPython environment, execute External commands or start another program in the Python program.
This article describes in detail how to execute system commands in Python. I will not talk much about it below. Let's take a look at the details.
(1) OS. system ()
This method calls standard C'ssystem()
Function, which only runs system commands on a sub-terminal, but 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 information object after execution. The result is returned through a pipeline file.
>>> output = os.popen('cat /proc/cpuinfo') >>> output <open file 'cat /proc/cpuinfo', mode 'r' at 0x7ff52d831540> >>> print output.read() processor : 0 vendor_id : AuthenticAMD cpu family : 21 ... ... >>><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 (status) returned by using this method in unix-like systems is different from the return value after script or command execution. This is because the OS is called. for the sake of wait (), you have to find out the implementation of the system wait. The correct return value (status) is required. You only need to perform the right shift of the return value by 8 bits.
NOTE 2:Subprocess is recommended when the command execution parameters or responses contain Chinese characters.
(4) subprocess Module
This module is a powerful sub-process management module and is a replacementos.system
,os.spawn*
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 68 drwxrwxr-x 3 xl xl 4096 Feb 8 05:00 com drwxr-xr-x 2 xl xl 4096 Jan 21 02:58 Desktop drwxr-xr-x 2 xl xl 4096 Jan 21 02:58 Documents drwxr-xr-x 2 xl xl 4096 Jan 21 07:44 Downloads ... ... >>>
Summary
The above is all the content of this article. I hope the content of this article has some reference and learning value for everyone's learning or work. If you have any questions, please leave a message to us, thank you for your support.