Python,subprocess Module (supplemental)

Source: Internet
Author: User

1.subprocess module, foreplay
res = Os.system (' dir ') prints to screen, res is 0 or not 0
Os.popen (' dir ') returns a Memory object, equivalent to a file stream
A = Os.popen (' dir '). Read () A is stored in the execution result output.

Python2.7 Commands Module Commands.getstatusoutput (' dir ') returns the tuple, the first element is state 0 for success, the second is the result
Windows is not good to use, just Linux useful




subprocess module, replacement Os.system, etc.

Subprocess.run ([' DF ', '-h ']) when the parameter is passed, the Python parsing, if there is a pipe character is not
Subprocess.run (' df-h | grep sda1 ', shell=true) shell=true means that you don't need to parse the Python and give the string directly to the shell
Python3.5 only appeared subprocess.run
The commands for terminal input are divided into two types:
Input can be output, such as: ifconfig
Input to an environment that relies on re-entry, such as: Python

Common subprocess

No pipe
Retcode = Subprocess.call ([' ls ', ' l ']) successfully returned 0, non-successful return 0
Subprocess.check_call ([' ls ', '-l ']) execution successfully returns 0, execution error thrown exception
Subprocess.getoutput (' Ls/bin/ls ') receives the string Format command, returning only the result
res = subprocess.check_output ([' ls ', '-l ']) execution successfully returned execution result, unsuccessful error
Subprocess.getstatsoutput (' Ls/bin/ls ') returns Ganso (1, '/bin/ls '), first state, second result

The above method, the bottom is the package Subprocess.popen
Example
res = Subprocess.popen (' ifconfig | grep 192 ', shell=true)
Res
<subprocess.popen Object at ox7f2131a>
Res.stdout.read () can't read it
To read it out to the standard output, first to the pipeline pipe and then to stdout Python and shell is two processes can not communicate independently, must be provided through the operating system of the pipeline
The pipe can be used to save the results to stdin stdout stderr
Subprocess.popen (' ifconfig | grep 192 ', shell=true,stdout=subprocess. PIPE)
Res.stdout.read () can be read out.
Subprocess.popen (' ifconfig | gr1111ep 192 ', shell=true,stdout=subprocess. PIPE)
An error will print directly. You can stderr save stderr=subprocess if you don't want to print errors. PIPE


Poll () Check if child process has terminated. Returns ReturnCode
---------
Res=subprocess.popen ("Sleep 10; echo ' Hello ', shell=true,stdout=subprocess. Pipe,stderr=subprocess. PIPE)
do not respond to the execution, do not know whether the card master or finished
each tune subprocess execute the linux command, the equivalent of starting a new shell, start a new process, execute a command and other results
if the command takes half an hour, I do not know whether it is the card master or finished, you can Res.poll () return none indicates that the execution has not finished, return 0 means that the
Res.wait () waits for the end and then returns 0
----------
Terminate () kills the process. Res.terminate ()
Wait () Wait for the child process to terminate. Returns ReturnCode attribute
Communicate () waiting for the end of the task is useless. Python as parameter, enter Python into environment
stdin standard input
stdout standard output
stderr standard error
PID the process ID of the child process


-----Available Parameters
Args:shell command, which can be a string or sequence type
BufSize: Specify buffer, 0 unbuffered, 1 row buffer, other buffer size negative system buffering
Stdin,stdout,stderr: Standard input, output, error handle
PREEXEC_FN: Valid only on UNIX platforms, used to specify an executable object that will be called before the child process is run
CLOSE_SFS: Under the Windows platform, if CLOSE_SFS is set to true, the newly created child process will not inherit the parent process's input, output, error pipe
You cannot set Close_fds to true while redirecting the standard input, output, and error of child processes

Shell: Ibid.
Cod: Used to set the current directory of the child process
ENV: The environment variable used to specify the child process. If env=none, the environment variables of the child process are inherited from the parent process
Universal_newlines: Different system line breaks different,true-> agree to use \ n
Startupinfo and Createionflags are only valid under Windows
will be passed to the underlying CreateProcess () function to set some properties of the child process,
Such as: the appearance of the main window, the priority of the process, etc.


Subprocess Automatic password entry for sudo
For example python inside execute sudo apt-get install vim (Linux inside to enter password)
Should echo ' 123 ' in Linux | Sudo-s iptables-l
Python direct Subprocess.popen ("echo ' 123 ' | Sudo-s iptables-l ", shell=true)

Python,subprocess Module (supplemental)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.