GPU queuing script
python script
GPU queuing script ---- once the GPU is idle, the script execution program is triggered
reference resources: GPU queuing script (python script)
cmd = 'bash run.sh' this sentence sets the python script to execute
import os import sys import time cmd = 'bash run.sh' #Set script to run def gpu_info(): gpu_status = os.popen('nvidia-smi | grep %').read().split('|') gpu_memory = int(gpu_status[2].split('/')[0].split('M')[0].strip()) gpu_power = int(gpu_status[1].split(' ')[-1].split('/')[0].split('W')[0].strip()) return gpu_power, gpu_memory def narrow_setup(interval = 2): gpu_power, gpu_memory = gpu_info() i = 0 while gpu_memory > 10000 or gpu_power > 100: #set waiting condition gpu_power, gpu_memory = gpu_info() i = i % 5 symbol = 'monitoring: ' + '>' * i + ' ' * (10 - i - 1) + '|' gpu_power_str = 'gpu power: %d W |' % gpu_power gpu_memory_str = 'gpu memory: %d MiB |' % gpu_memory sys.stdout.write('\r' + gpu_memory_str + '\t' + gpu_power_str + '\t' + symbol) sys.stdout.flush() #sys.stdout.flush() is used to display the contents of the buffer time.sleep(interval) i += 1 print("\n" + cmd) os.system(cmd) if __name__ == '__main__': narrow_setup()
You can listen to NVIDIA SMI information to wait for an opportunity to trigger the python script. When the GPU's video memory and power consumption are lower than a certain value, the python script will be triggered.
shell script
You can add training model statements directly to the shell script
#!/bin/bash var=0 while [ $var -eq 0 ] do count=0 for i in $(nvidia-smi --query-gpu=memory.used --format=csv,noheader,nounits) do if [ $i -lt 500 ] then echo 'GPU'$count' is available' bash run.sh #Statement of training model var=1 break fi count=$(($count+1)) #echo $count done done
Linux commands
more command
Use the more command to view the pagination display of files
(more +N file_name starts from the specified line)
(more -N file_name sets the number of lines displayed on each screen)
- Spacebar: view the next screen
- Enter: scroll down one line
- b key: look forward to one screen
- q key: exit
Pipe symbol|
Command format: command A | command B (that is, the correct output of command A is the operation object of command b)
Cat file | more (first show the contents in the file, and then the more instruction processes the contents of the file)
grep instruction
grep (global search regular expression(RE) and print out the line): search the text using regular expressions and print out the matching lines.
id name java 1 90 90 2 lisi 89 3 wangw 93 4 zhao 82
grep -c String file name: calculates the number of lines found in the search string grep -c "name" student.txt #1
grep -o String file name: indicates what matches grep -o "zhang" student.txt # grep -o "zh" student.txt #zh
grep -i String file name: case insensitive. Print a line of information grep -i "zh" student.txt #4 zhao 82
grep -n String file name: display line number grep -n "zh" student.txt 5:4 zhao 82
cut instruction
cut: extract a column
cut -f column number: which column is extracted
-d separator: divides the column according to the specified separator
awk instruction
Shell Scripting
Shell script programming for Linux (1)
Getting started with shell Scripting
Shell is a command interpreter and a user interface of Unix operating system.
Shell is also a programming language, namely shell script. Shell is a script language for interpretation and execution, which can directly call linux commands. Multiple shells can exist in a system. You can view the shells installed in the system through the cat /etc/shells command. Different shells may support different command syntax.
1, shell type
The operating system kernel and shell are independent packages and can be replaced. Different operating systems use different shells; Different shells can be used on the same kernel.
Common shell s are divided into two main streams:
sh:
- Bourne shell (sh), Solaris, hpux default shell
- Bourne again shell (bash), the default shell of Linux system
csh:
- C shell(csh)
- tc shell(tcsh)
View shell used
echo $SHELL #/bin/bash
shell environment definition
Temporary environment variable: the so-called temporary environment variable refers to the variable that takes effect in the current login environment. After the user logs in to the system, the environment variables defined directly on the command line can only be used in the current login environment. After exiting the system, the environment variable will not be used at the next login
Permanently effective environment variable: by writing the environment variable definition into the configuration file, the system will automatically define it every time the user logs in, so there is no need to redefine it on the command line. Common configuration files that define environment variables are as follows:
/The etc/profile is effective for all users of the system. This file applies to the definition of environment variables when all users log in to the system each time
$HOME_ name/.bash_ The profile is effective for a specific user, and $home is the user's host directory. When the user logs in to the system, first inherit the definition in the / etc/profile file, and then apply $home /. Bash_ Definition in profile file
System predefined environment variables: system environment variables are valid for all users, such as $PATH, $HOME, $SHELL, $PWD, etc. print the above system environment variables with echo command
echo $PATH #/opt/conda/bin:/usr/local/nvidia/bin:/usr/local/cuda/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin echo $PWD #/workspace echo $SHELL #/bin/bash echo $HOME #/root
shell Scripting
Like traditional programming languages, simultaneous interpreting shell provides many features that make Shell Scripting more useful.
Create shell script
- First line: the first line is on the left side of the first line of the script, indicating the shell interpreter to be called by the script. The content is as follows: #/ bin/bash, #! The symbol can be recognized by the kernel is the beginning of a script. This line must be located at the first line of the script, / bin / Bash is the absolute path of the bash program. Here, it means that the subsequent contents will be interpreted and executed by the bash program.
- Note: the comment symbol # is placed in front of the content to be commented. Multi line comment: multi line code to be commented: < < EOF EOF embeds the contents of multi line comments inside
- Content: executable content and shell structure
Permissions for shell scripts
Generally, scripts created by default do not have execution permission. You cannot execute without permission. You need to give executable permission.
chmod +x test.sh
Execution of shell script
1. Enter the absolute path or relative path of the script
- /workspace/test.sh
- ./test.sh
2.bash or sh + script (when the script has no x permission, the root and file owner can execute normally through this method)
- bash test.sh
- sh test.sh
3. Add "." or source before the path of the script
- source /workspace/test.sh
- . test.sh
The first and second will create a new bash, and the variables in different bashs cannot be shared. However, using. / test.sh is executed in the same shell.
2, shell variable
Variable: a way for the shell to transfer data. It is used to represent the symbolic name of each value. When the shell script needs to save some information, store it in a variable.
Variable setting rules:
- Variable names can be composed of letters, numbers and underscores, but cannot start with numbers. Environment variable names are recommended to be capitalized for easy distinction
- In bash, the default type of variables is string type. If you want to perform numerical operation, you must specify the variable type as numeric type
- Variables are connected with an equal sign, and there can be no spaces on the left and right sides of the equal sign
- If there are spaces in the value of the variable, you need to use single quotation marks or double quotation marks
Variable classification:
Variables in Linux Shell are divided into user-defined variables, environment variables, location parameter variables and predefined variables. You can view all variables in the system through the set command.
- System variable: save data related to system operating environment$ HOME, $PWD, $SHELL, $USER, etc.
- Location parameter variable: it is mainly used to transfer parameters or data to the script. The variable name cannot be customized and the function of the variable is fixed.
- Predefined variable: it is a variable defined in Bash. The variable name cannot be customized, and the function of the variable is fixed.
User defined variable
User defined variables start with letters or underscores, and are composed of letters, numbers or underscores. The meanings of upper and lower case letters are different, and the length of variable names is unlimited. Read only type variables, using the readonly command
Set variables. It is customary to name variables in uppercase letters. Variable names begin with letters and cannot be numbers.
Variable call. When using a variable, prefix the variable name with "$". Use the echo command to view the variable value, eg: echo $A
Variable assignment,
- Assignment during definition: variable = value (no spaces on both sides of the equal sign) eg: STR="hello world" A=9
- Assign the execution result of a command to a variable:
- A=`ls -la ` backquotes, run the command inside, and return the result to variable a
- A=$(ls -la) is equivalent to backquotes eg: aa=$((4+5)) bb=`expr 4 + 5`
- Assign a variable to another variable eg: A=$STR
Variable superposition,
aa=123 echo $aa #123 cc="$aa"456 echo $cc #123456 dd=${aa}789 echo $dd #123789
The difference between single quotation marks and double quotation marks:
Phenomenon: all the contents in single quotation marks will be output, while the contents in double quotation marks will change
Reason: single quotation marks will take all special characters out of meaning
- When taking values for variables, use the "#" symbol to take values for strings
- Extract the substring and use the string interception command to extract part of the string str:k1:k2
- The search string is used to find the position of the character. The output result is the data position of the character in the string. If multiple characters are searched, which letter appears first is calculated first
NUM=10 SUM="$NUM hehe" echo $SUM #10 hehe SUM2='$NUM hehe' echo $SUM2 #$NUM hehe string="abcd" echo ${#string} #4 string="this is a test" echo ${string:2:6} #is is string="this is a test" echo `expr index "$string" "it"` #1
List all variables, set
Delete variable, unset NAME (unset undo variable, for readonly B=2 declared static variable B=2, unset is not allowed)
A user-defined variable whose scope is the current shell environment
environment variable
User defined variables only take effect in the current shell, while environment variables will take effect in the current shell and its child shells. If environment variables are written to the corresponding configuration file, then this environment variable will take effect in all shells.
export variable name = variable value Declarative variable
Predefined variables
$? The return value of executing the previous command. If the execution is successful, 0 will be returned. If the execution fails, non-0 will be returned
$$ The process number (PID) of the current process, that is, the process number generated when the current script is executed
$! The process number (PID) of the last process running in the background, and the last process put into the background for execution
expr command: four operations and string operations
String operation ability of expr
- match Match string matches the REGEXP string in REGEXP string and returns the length of the matching string
- substr substr STRING POS LENGTH gets a string of LENGTH from the POS location
- index index STRING SUBSTR finds the starting position of the substring
- length length STRING calculates the length of a string
3, shell array
In bash, only one-dimensional arrays are supported, the size of the array is not limited, and multi-dimensional arrays are not supported. Similar to C language, the subscripts of array elements are numbered from 0. The subscript is used to obtain the elements in the array. The subscript can be an integer or arithmetic expression, and its value should be greater than or equal to 0.
Define array: in the shell, use () to define the array, and the elements in the array are separated by the "space" symbol. The general form of definition array is:
Three definition forms of array; The read array and read variable names are the same, and the $symbol is used; The method for obtaining the length of an array is the same as that for obtaining the length of a string.
#!/bin/bash array_name=(value1 value2 value3 value4) array_test=( value1 value2 value3 value4 ) array_text[0]=value0 array_text[1]=value1 array_text[3]=value3 valuen=${array_name[2]} echo $valuen #Output value3 echo ${array_name[n]} #Output value1 echo ${array_name[@]} #Output value1 value2 value3 value4 length=${#array_name[@]} echo $length #Output 4 length=${#array_name[*]} echo $length #Output 4 length=${#array_name[0]} echo $length #Output 6
4, shell pass parameters
When executing a shell script, pass parameters to the script. The format of parameters obtained in the script is: $n. N represents a number, 1 is the first parameter of executing the script, 2 is the second parameter of executing the script, and so on
When using the shell to pass parameters, you need to use the following characters to process the parameters
- $#: number of parameters passed to the script
- $$: ID number of the current process in which the script is running
- $!: ID number of the last process running in the background
- $?: Displays the exit status of the last command. 0 indicates no error, and any other value indicates an error
- $*: displays all parameters passed to the script in a single string
- $@: same as *, add quotation marks and return each parameter in quotation marks
#!/bin/bash echo "Pass parameter instance!"; echo "File name of the execution:$0"; echo "The first parameter is:$1"; echo "The second parameter is:$2"; echo "The third parameter is:$3"; echo "The number of parameters is: $#"; echo "The process in which the script runs ID number:$$"; echo "Of the last process running in the background ID number:$!"; echo "Displays the exit status of the last command:$?"; echo "Output parameters passed to script: $*" echo "Output parameters passed to script: $@" #Execute bash test.sh 1 2 3 #output Pass parameter instance! File name of the execution:test.sh The first parameter is:1 The second parameter is:2 The third parameter is:3 Number of parameters: 3 The process in which the script runs ID number:24610 Of the last process running in the background ID number: Displays the exit status of the last command:0 Output parameters passed to script: 1 2 3 Output parameters passed to script: 1 2 3
5, shell operator
Shell operator types. The shell also supports multiple operators
- Arithmetic operator
- Relational operator
- Boolean operator
- Logical operator
- String operator
- File test operator
The shell needs to use these operators in combination with other commands and tools. The two commonly used tools for using arithmetic operators are awk and expr
- Spaces must be used between expressions and operators (must be written as 3 + 2)
- The complete expression should be contained by two `
Operators and numbers must be separated by spaces
Arithmetic operator
+ - * / % = == !=
Note: the multiplication sign (*) in the arithmetic operator must be preceded by a backslash to realize multiplication
Relational operator
The shell uses special characters to represent relational operators, and only supports numbers, not strings, unless the string is a number
-eq -ne -gt -lt -ge -le
Boolean operator
! (non operational) - o (or operation) - a (and operation)
Logical operator
&&(AND in logic) || (OR in logic)
Here, two levels of [] symbols are used to save the results of two relational operations in conditional sentences
String operator
= != - z -n $ (check whether the string is empty)
File test operator
The file test operator in the shell is used to detect various properties of files in unix like systems
#!/bin/bash val=`expr 3 + 2` echo "The sum of the two numbers is: $val" #The sum of the two numbers is: 5 a=10 b=20 if [ $a -eq $b ] then echo "$a -eq $b : a be equal to b" else echo "$a -eq $b : a Not equal to b" fi #10 -eq 20: a is not equal to b if [ $a -ne $b ] then echo "$a -ne $b : a Not equal to b" else echo "$a -ne $b : a be equal to b" fi #10 -ne 20: A is not equal to b a=10 b=20 if [ $a -eq 10 -o $b -eq 20 ] then echo "TRUE" else echo "FALSE" fi #TRUE if [[ $a -lt 100 && $b -gt 100 ]] then echo "return true" else echo "return false" fi #Return false a="abc" b="efg" if [ $a != $b ] then echo "$a != $b : a Not equal to b" else echo "$a != $b : a be equal to b" fi #abc != EFG: A is not equal to b file="./test.sh" if [ -r $file ] then echo "File readable" else echo "File unreadable" fi #File readable
6, Commands in shell programming
Echo command (echo command is used for string output in shell, and the calling format is echo string)
> Redirect results to file
-e Indicates that escape is on
#!/bin/bash echo "this is a test" echo \"this is a test\" name="ohuohuo" echo "your name is $name" echo -e "Right! \n" # -e means to enable escape echo "this is other line" echo "this is a test" > testfile echo `date` #Execute command bash test.sh #Output: this is a test "this is a test" your name is ohuohuo Right! this is other line Mon 18 Oct 2021 10:06:50 PM HKT
Printf command (the printf command in the shell is the same as that in C language, but the newline symbol will not be called automatically. The calling format is printf format string [arguments...] (format string format control string, arguments parameter list))
The printf command can use more powerful escape characters
echo "Hello, Shell" #Output: Hello, Shell printf "Hello, Shell\n" #Output: Hello, Shell
test command
The test command in the shell is used to check whether a condition is true. You can test values, characters and files
Numerical test command table
parameter | explain |
-eq(equal) | Equal to true |
-ne(no equal) | Not equal to true |
-gt(great than) | Greater than is true |
-ge(great and equal) | Greater than or equal to is true |
-lt(low than) | Less than is true |
-le(low and equal) | True if less than or equal to |
#!/bin/bash num1=100 num2=100 if test $[num1] -eq $[num2] then echo 'Two numbers are equal!' else echo 'The two numbers are not equal!' fi #Output: two numbers are equal!
String test table
parameter | explain |
= | Equal to true |
!= | True if not equal |
-z string | True if the string length is zero |
-n string | String length bu'wei'l |
num1="name" num2="function" if test $num1 = $num2 then echo 'Two strings are equal!' else echo 'Two strings are not equal!' fi #Output: two strings are not equal!
Document test form
parameter | explain |
-e file name | True if the file exists |
-r file name | True if the file exists and is readable |
-w file name | True if the file exists and is writable |
-x file name | True if the file exists and is executable |
-s file name | True if the file exists and has at least one character |
-d file name | True if the file exists and is a directory |
-f file name | True if the file exists and is a normal file |
-c file name | True if the file exists and is a character type special file |
-b file name | True if the file exists and is a block special file |
#!/bin/bash if test -e ./test.sh then echo 'File already exists!' else echo 'File does not exist!' fi #Output: file already exists!
7, shell process control
As a script language, shell has its own process control, and the process control in shell is mainly composed of conditions and loops.
if else condition
The condition template is if - then - elif - then - else - fi
#!/bin/bash num1=$[6] num2=$[8] if test $[num1] -eq $[num2] then echo "Two numbers are equal" else echo "The two numbers are not equal" fi #The two numbers are not equal
case condition
- The value needs to be followed by in
- The first mock exam must be closed with right brackets.
- Use after each mode;; End of symbol
- If the corresponding pattern is not found. End with * and jump out of case
- case needs to end with esac, which is similar to the switch... case statement in C language
There are two commands to jump out of a loop in case: break and continue
break command: allow to jump out of all loops (abort the execution of all subsequent loops)
continue command: it will not jump out of all loops, but only the current loop, which is the same as other types of languages
#!/bin/bash echo 'Enter a number between 1 and 4:' echo 'The number you entered is:' read num case $num in 1) echo 'You chose 1' ;; 2) echo 'You chose 2' ;; 3) echo 'You chose 3' ;; 4) echo 'You chose 4' ;; *) echo 'You did not enter 1-4 Number between' ;; esac #Output: Enter a number between 1 and 4: The number you entered is: 3 You chose 3 while : do echo "Input 1-4 Number between:" read num case $num in 1|2|3|4) echo "The number you entered is $num !" ;; 5) echo "The number you entered is 5" continue echo "game over" ;; *) echo "The number you entered is not 1-5 Between! game over" break ;; esac done #output Input 1-4 Number between: 5 The number you entered is 5 Input 1-4 Number between: 3 The number you entered is 3 ! Input 1-4 Number between: 6 The number you entered is not 1-5 Between! game over
for loop
Condition template for VaR in Item1 Item2... Itemn -- do command1 -- done
while Loop
Condition template while condition -- do command -- done
until loop
Condition templateuntil condition -- do command -- done
for num in 1 2 3 4 5 do echo "The value is : $num" done #Output: The value is : 1 The value is : 2 The value is : 3 The value is : 4 The value is : 5 num=1 while(( $num <= 5 )) do echo $num let "num++" done #Output: 1 2 3 4 5 a=0 until [ ! $a -lt 5 ] do echo $a a=`expr $a + 1` done #output 0 1 2 3 4
8, shell function
The shell in Linux can also define functions, and then invoke the execution related shell commands in the function to complete the function.
All functions must be defined before use, because the shell interpreter executes layer by layer. When the shell interpreter finds the defined function, it will find the corresponding function and execute it.
[function] funname[()] { action; [return int;] } function fun()Represents a function with return parameters fun()Represents a function with no return parameters use return You can return parameter values. If not used, the result of the last command will be used as the return value by default
#!/bin/bash FunReturn(){ echo "Add two numbers..." echo "Enter the first number:" read num echo "Enter the second number:" read anothernum echo "The two numbers are $num and $anothernum " return $(( $num + $anothernum )) #Return values separately } FunReturn #Call function echo "The sum of the two numbers entered is $? !" #Use wildcards to get the return value of the previous instruction #output Add two numbers... Enter the first number: 3 Enter the second number: 4 The two numbers are 3 and 4, respectively The sum of the two numbers entered is 7 !
9, shell redirection
shell redirection in Linux commands
Python scripting
Use of sys, os and time modules of python
sys module
1. sys.argv: pass parameters from outside the program to the program.
The location parameter argv[0] represents the PY file itself. Run the method python test.py with parameter 1 and parameter 2
# test.py import sys if __name__ == "__main__": self = sys.argv[0] name = sys.argv[1] age = sys.argv[2] print(self, name, age) # Run program python test.py xiaoming 18
2. sys.getdefaultencoding(): get the current system code. Generally, ascii is the default.
print(sys.getdefaultencoding())
3. sys.path: get the string collection of the specified module search path
print(sys.path)
4.sys.platform: obtain the current system platform
print(sys.platform)
5.sys.exit(): the interpreter will exit automatically at the end of the main program. However, if you need to exit the program halfway, you can call the sys.exit() function and return it with an optional integer parameter to the program calling it, indicating that the call to sys.exit() is captured in the main program
import os if __name__ == "__main__": for i in range(1, 10): print("The first%s Times:"%i) if i == 5: print("Fifth exit") sys.exit(0)
os module
1.os.name: judge the platform being used. Windows returns' nt 'and Linux returns' posix‘
print(os.name) #posix
2.os.getcwd(): get the current working directory
print(os.getcwd()) #/workspace/CCF_2021/question_matching
3. os.listdir(): specify all file and directory names under all directories
print(os.listdir('.'))
4. os.remove(): deletes the specified file
os.remove('test.txt')
5.os.rmdir(): delete the specified directory (directories cannot be nested)
os.rmdir('test')
6.os.mkdir(): create directory (this method can only create one layer directory, and os.makedirs() is used for recursive establishment)
os.mkdir('test') os.makedirs('test/test')
7.os.path.isfile(): judge whether the specified object is a file. True if yes, False otherwise
print(os.path.isfile('test.py'))
8.os.path.isdir(): judge whether the specified object is a directory. True if yes, False otherwise
print(os.path.isdir('test'))
9.os.path.exists(): judge whether the specified object exists. If yes, return True; otherwise, false (judge whether a folder or file exists)
os.path.exists(test)
10.os.path.split(): returns the directory and file name of the path
os.path.split('/workspace/CCF_BDCI2021/question_matching/data') #Output: ('/ workspace / ccf_bdci2021 / question_matching','data ')
11.os.getcwd(): get the current working directory
print(os.getcwd())
12.os.system(): execute shell command
var = 123 os.environ['var'] = str(var) #Note that "string" is in [] here os.system('echo $var') #Output: 123 0
13.os.chdir(): used to change the current working directory to the specified directory (change the working directory to the specified directory)
print(os.getcwd()) #Output: / workspace/CCF_BDCI2021/question_matching/test os.chdir('/workspace') print(os.getcwd()) #Output: / workspace
14.os.path.getsize(): get the size of the file
print(os.path.getsize('test.py'))
15.os.path.abspath('.'): get absolute path
print(os.path.abspath('.')) #Output: / workspace/CCF_BDCI2021/question_matching
16.os.path.join(path, name): connection directory and file name
os.path.join('/workspace/CCF_BDCI2021/question_matching', 'file') #Output: '/ workspace/CCF_BDCI2021/question_matching/file'
17.os.path.realpath(): get the directory where the file is located
import os import sys if __name__ == "__main__": print(sys.argv[0]) #File name print(os.path.realpath(sys.argv[0])) #Path to file print(os.path.split(os.path.realpath(sys.argv[0]))) #Separate the path and file name of the file print(os.path.split(os.path.realpath(sys.argv[0]))[0]) #Path to output file #Output: test.py /workspace/CCF_BDCI2021/question_matching/test.py ('/workspace/CCF_BDCI2021/question_matching', 'test.py') /workspace/CCF_BDCI2021/question_matching
18.os.path.basename(): get the file name in the path os.path.dirname(): get the file path name
print(os.path.basename('/workspace/CCF_BDCI2021/question_matching/test.py')) #Output: test.py print(os.path.dirname('/workspace/CCF_BDCI2021/question_matching/test.py')) #Output: / workspace/CCF_BDCI2021/question_matching
time module
Get time
import time ticks = time.time() print(ticks) localtime = time.localtime(time.time()) print(localtime) localtime = time.asctime(time.localtime(time.time())) print(localtime) #1634397810.7200205 #time.struct_time(tm_year=2021, tm_mon=10, tm_mday=16, tm_hour=23, tm_min=23, tm_sec=55, tm_wday=5, tm_yday=289, tm_isdst=0) #Sat Oct 16 23:24:41 2021
format date
import time print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) print(time.strftime("%a %b %d %H:%M:%S %Y", time.localtime())) import calendar cal = calendar.month(2021, 10) print(cal) #output 2021-10-16 23:39:59 Sat Oct 16 23:40:51 2021 October 2021 Mo Tu We Th Fr Sa Su 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
python scripting practice
sys.stdout.write() writes str to the output stream (only one str can be output, output intact, and '\ n' will not be added by default)
sys.stdout.flush() is used to display the contents of the buffer (if a newline character is added to the contents of the buffer, stdout will automatically output the contents of the buffer)
Executing shell commands in python
- Use the os.system() command, os.system('cat /proc/cpuinfo ')
- Use the os.popen() command, output = os.popen('cat /proc/cpuinfo ') print(output.read()), through os.popen(), the object of file read is returned. read() can see the output executed, but the return value executed by the program cannot be read.