Python Learning ———— Module subprocess

Source: Internet
Author: User

subprocess Module

The subprocess module targets to start a new process and communicate with it.

1. Call: Executes the program, waits for it to complete, returns the status code.

Importsubprocess
Ret1 = Subprocess.call (["CP","-P"],Shell=True)
Ret2 = Subprocess.call (["CP","-P"],Shell=False)

Shell = True allows the shell to be a string form.


def Call (*popenargs, **kwargs):
return Popen (*popenargs, **kwargs). Wait ()

2, Call_check () calls the preceding call () function, and throws an exception if the return value is nonzero.


defCheck_call (*popenargs, **kwargs):
Retcode = Call (*popenargs, **kwargs)
ifRetcode:
cmd = Kwargs.get ("args")
offcmd isNone:
cmd = popenargs[0]
RaiseCalledprocesserror (Retcode, cmd)
return0

3, Check_output (): Executes the program, if the return code is 0, returns the execution result.

defcheck_output (*popenargs, **kwargs):
if' stdout 'inchKwargs:
RaiseValueError(' stdout argument not allowed, it'll be overridden. ')
Process = Popen (stdout=pipe, *popenargs, **kwargs)
Output, Unused_err = Process.communicate ()
Retcode = Process.poll ()
ifRetcode
cmd = Kwargs.get ("args")
ifcmd isNone:
cmd = popenargs[0]
Raisecalledprocesserror (retcode, CMD,Output=Output)
returnOutput

4. Subprocess also provides a very important class Popen: Execute complex system commands.

classPopen (Object):
def__init__( Self, args, bufsize=0, executable=None,
stdin=None, stdout=None, stderr=None,
preexec_fn=None, close_fds=False, Shell=False,
Cwd=None, env=None, universal_newlines=False,
startupinfo=None, creationflags=0):

Args
The shell command can be a string or a list
BufSize 0 unbuffered, 1 row buffer, other buffer size, negative system buffering
Executable Generally not
stdin stdout stderr Standard output, output, error handle
Preexec_fn Executes only on UNIX platforms, specifying an executable object that is called before the child process executes
Close_fds under the Windows platform, if Close_fds is set to true, the newly created child process will not inherit the input, output, and error pipes of the parent process.
Therefore, you cannot set Close_fds to true while redirecting the standard input, output, and error (stdin, stdout, stderr) of the child process.
Shell Ditto
Cwd Used to set the current directory of the child process
Env Environment variables for setting child processes
Universal_newlines Various newline characters are set to \ n
Startupinfo struct passed to CreateProcess under window, only valid under Windows
Creationflags Under Windows, passing Create_new_console creates its own console window, which is valid under Windows

Methods of Popen:

Poll ()
Check if end, set return value
Wait () Wait for end, set return value
Communicate ()
parameter is standard input, return standard output and error
Send_signal ()
Send a signal, mainly used under Linux
Terminate ()
Terminating signal
Kill ()
Kill process
Pid
Process ID
ReturnCode
Process return value
stdin
stdout
stderr
parameter, it is useful to specify pipe in the

Example:

Import subprocessobj = subprocess. Popen (["Python"], stdin=subprocess. PIPE, Stdout=subprocess. PIPE, Stderr=subprocess. PIPE) Obj.stdin.write (' Print 1 \ n ') obj.stdin.write (' Print 2 \ n ') obj.stdin.write (' Print 3 \ n ') obj.stdin.write (' Print 4 \ n ') obj.stdin.close () Cmd_out = Obj.stdout.read () obj.stdout.close () Cmd_error = Obj.stderr.read () obj.stderr.close () Print Cmd_outprint Cmd_error

Reference URL: http://www.cnblogs.com/wupeiqi/articles/4963027.html

Python Learning ———— Module subprocess

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.