Python calls to execute Linux system commands (four methods)

                                Python calls to execute Linux system commands (four methods)

Python, as a scripting language and glue language, naturally has its glue characteristics, such as the combination of Python and Linux systems. For example, when using Python to write automated operation and maintenance scripts, it is inevitable to interact with the Linux system, such as , Query a file in the Linux system, then modify the file and run it (assuming you have runnable permissions).

One of the commendable parts of Python is that it has a very complete class library. This is really not bragging, only you can't think of it. There are basically no libraries that it does not have, such as scientific computing libraries numpy, pandas, or libraries that interact with the system. The os library, or the selenium library for automated testing, etc., I think the founder of Python may not know how many libraries there are in Python. (The Python community is too powerful!!!) So, if Python needs to call Linux system commands, such as ls, df, free, ps, such commands naturally need to be combined with the special library os that interacts with the system. One way is to directly manipulate the process, so naturally it is the subprocess library. In other words, we want Python to be able to call Linux system commands, that is, Python interacts with the Linux system, either we need to use the os library, or we need to use the subprocess library, and there is a less commonly used commands library~~~! ! ! @~~~~

Python's os module, as the name implies, the meaning of opera system is no doubt. This module is a built-in module of Python, which can also be said to be a built-in library. The functions in this module are naturally built-in functions. To interact with system commands, we need to use its system() and popen(). A function, or use the commands module, or use the subprocess module. The first two functions and the commands module are relatively obsolete. The subprocess module is now the official recommendation or it can be said that the subprocess module is strongly recommended.

 

(1) os.system (direct call at the system level). This call is quite direct and is performed synchronously. The program needs to block and wait for the return. The return value depends on the system, and directly returns the return value of the system call, so windows and linux are not the same.

Only run the system command in a sub-terminal, but cannot get the return information after the command is executed

 

(2) os.popen (new thread opening method), it can be seen that the popen method obtains terminal output through p.read(), and popen needs to close close(). When the execution is successful, close() does not return any value. When it fails, close() returns the system return value. It can be seen that the way it gets the return value is different from os.system .

This method not only executes the command but also returns the information object after execution. The advantage is that the returned result is assigned to a variable, which is convenient for the processing of the program.

 

(3) Use module commands (python3 is invalid)

 

(4) Use the module subprocess (currently recommended in the Python documentation) to directly call the command, and the return value is the system return. shell=True means that the command will eventually run in the shell. For security reasons, it is not recommended to use shell=True in the Python documentation. ​​​​​​​

import os
import commands
print('=============================ls')
os.system('ls -al /')
print('===========df')
df = os.popen('df -ah').read()
print(df)
print('=========================free')
a = commands.getoutput("free -mh")
print(a)

The output result is:

=============================ls
total 28
dr-xr-xr-x.  17 root root  244 Jan 24 12:11 .
dr-xr-xr-x.  17 root root  244 Jan 24 12:11 ..
-rw-r--r--    1 root root    0 Jan 24 12:11 .autorelabel
lrwxrwxrwx.   1 root root    7 Jan 24 11:12 bin -> usr/bin
dr-xr-xr-x.   5 root root 4096 Jan 24 12:11 boot
drwxr-xr-x   19 root root 3320 Feb  1 09:29 dev
drwxr-xr-x. 138 root root 8192 Feb  1 09:29 etc
drwxr-xr-x.   2 root root    6 Nov  5  2016 home
lrwxrwxrwx.   1 root root    7 Jan 24 11:12 lib -> usr/lib
lrwxrwxrwx.   1 root root    9 Jan 24 11:12 lib64 -> usr/lib64
drwxr-xr-x.   2 root root    6 Nov  5  2016 media
drwxr-xr-x.   3 root root   19 Jan 24 11:34 mnt
drwxr-xr-x.   4 root root   34 Jan 24 11:58 opt
dr-xr-xr-x  229 root root    0 Feb  1 09:29 proc
dr-xr-x---.  11 root root 4096 Feb  1 09:30 root
drwxr-xr-x   39 root root 1200 Feb  1 09:29 run
lrwxrwxrwx.   1 root root    8 Jan 24 11:12 sbin -> usr/sbin
drwxr-xr-x.   2 root root    6 Nov  5  2016 srv
dr-xr-xr-x   13 root root    0 Feb  1 09:29 sys
drwxrwxrwt.  21 root root 4096 Feb  1 09:46 tmp
drwxr-xr-x.  13 root root  155 Jan 24 11:12 usr
drwxr-xr-x.  21 root root 4096 Jan 24 11:44 var
===========df
Filesystem      Size  Used Avail Use% Mounted on
rootfs             -     -     -    - /
sysfs              0     0     0    - /sys
proc               0     0     0    - /proc
devtmpfs        1.9G     0  1.9G   0% /dev
securityfs         0     0     0    - /sys/kernel/security
tmpfs           1.9G     0  1.9G   0% /dev/shm
devpts             0     0     0    - /dev/pts
tmpfs           1.9G  9.0M  1.9G   1% /run
tmpfs           1.9G     0  1.9G   0% /sys/fs/cgroup
cgroup             0     0     0    - /sys/fs/cgroup/systemd
pstore             0     0     0    - /sys/fs/pstore
cgroup             0     0     0    - /sys/fs/cgroup/pids
cgroup             0     0     0    - /sys/fs/cgroup/cpu,cpuacct
cgroup             0     0     0    - /sys/fs/cgroup/net_cls,net_prio
cgroup             0     0     0    - /sys/fs/cgroup/perf_event
cgroup             0     0     0    - /sys/fs/cgroup/freezer
cgroup             0     0     0    - /sys/fs/cgroup/memory
cgroup             0     0     0    - /sys/fs/cgroup/cpuset
cgroup             0     0     0    - /sys/fs/cgroup/hugetlb
cgroup             0     0     0    - /sys/fs/cgroup/blkio
cgroup             0     0     0    - /sys/fs/cgroup/devices
configfs           0     0     0    - /sys/kernel/config
/dev/sda6        70G  4.7G   66G   7% /
systemd-1          -     -     -    - /proc/sys/fs/binfmt_misc
debugfs            0     0     0    - /sys/kernel/debug
mqueue             0     0     0    - /dev/mqueue
hugetlbfs          0     0     0    - /dev/hugepages
nfsd               0     0     0    - /proc/fs/nfsd
/dev/sr0        4.3G  4.3G     0 100% /mnt/cdrom
/dev/sda3       5.0G   33M  5.0G   1% /home
/dev/sda2        20G  164M   20G   1% /var
/dev/sda1       497M  128M  370M  26% /boot
sunrpc             0     0     0    - /var/lib/nfs/rpc_pipefs
tmpfs           378M  4.0K  378M   1% /run/user/0
binfmt_misc        0     0     0    - /proc/sys/fs/binfmt_misc

=========================free
              total        used        free      shared  buff/cache   available
Mem:           3.7G        939M        1.8G        8.9M        1.0G        2.5G
Swap:          4.0G          0B        4.0G

The above is the system method of the os module, the popen method and the method of calling the Linux library from the commands library. The method of calling Linux system commands in subprocess will be added later. (People do not have a Python environment outside)

Guess you like

Origin blog.csdn.net/alwaysbefine/article/details/113485055