Share python execution using shell commands, pythonshell
1. OS. system (shell_command)
Output the execution result directly on the terminal and return the execution status 0, 1.
This function will start the process, execute the command in the sub-process, and return the exit status after the command is executed. If the command has execution content, it will be displayed in the standard output. This is actually implemented using the C standard library function system.
Disadvantage: This function needs to re-open a terminal when executing the command, and cannot save the command execution result.
os.system('cat /etc/passwdqc.conf')
2. OS. popen ()
Open a pipeline between the command process and the command process. The return value of this function is a file object that can be read or written (determined by the mode, the default mode is 'R '). If the mode is 'R', you can use the return value of this function to call read () to obtain the execution result of the command.
OS. system (cmd) or OS. popen (cmd). The former returns the exit code of the script, and the latter returns the output content during script execution. The actual usage depends on your needs.
tmp = os.popen('ls -l *').readlines()
3. commands. getstatusoutput (command)
Use the commands. getstatusoutput (command) function to execute the command and return a triple (status, output), indicating the return status and execution result of command Execution respectively. The command is actually executed in the {command;} 2> & 1 mode, so the output contains the console output information or error information. Output does not contain line breaks at the end.
(Status, output) = commands. getstatusoutput ("netstat-apn | grep {0} | awk '{{{ 1 }}' | xargs echo ". format (port, 'print $ 7') rr = re. compile (R' (\ d +)/Java') op = rr. findall (output) # Find all words containing 'java' for I in range (len (op): OS. system ("kill-9 {0 }". format (op [I]) # Kill the operating system according to the flag. system ("ps-ef | grep {0} | awk '{1}' | xargs kill-9 ". format (key, 'print $2 '))
Actual usagecommands.getstatusoutput(command)It is easy to use. Use the functions as needed.
Summary
The above is all the content shared in this article about how to execute shell commands in python. If you are interested, please refer to this site: python uses socket to implement multiple connections and ssh functions, Python basic exercises, user logon, code sharing, Python getting started with trigonometric functions, and collections, if you have any questions, you can leave a message at any time. The editor will reply to you in a timely manner. Thank you for your support!