The Subprocess module also provides a number of convenient ways to execute shell commands

Source: Internet
Author: User
Tags stdin python script

Now you can see that it handled the escape gracefully.

Attention

You can actually use a single string as a parameter in Shell=false, but it has to be the command program itself, which is no different from defining a args in a list. If you execute the string command directly when Shell=false, you will get an error:

>>> subprocess. Popen (' echo ' Hello world! "', Shell=false)
Traceback (most recent call last):
File" <stdin> ", line 1, in <mo Dule>
File "/usr/lib/python2.5/subprocess.py", line 594, __init__
Errread, errwrite)
File "/usr/lib/ python2.5/subprocess.py ", line 1147, in _execute_child
raise Child_exception
OSError: [Errno 2] No such file or dire Ctory
If we persist in using a string, Python will assume that the complete string is an executable program name, and there is actually no one called echo "Hello world!" The program, so the error. The correct procedure is to use the list to separate the parameters.
Check programs in PATH
Here's a way to find out where the program really is:
import OS
def whereis:
for PATH in Os.environ.get (' PATH ', ') . Split (': '):
If Os.path.exists (os.path.join (path, program)) and \
Not Os.path.isdir (path, program ):
Return Os.path.join (path, program)
return None
Let's use it to find out where the Echo program is:
>>> location = Whereis (' Echo ')
>>> if location was not None:
... print location
/bin/echo
This method can also check if there is a Python in the user's path The required program.

Of course you can also use the program Whereis in the command line to find the path to the program.

$ whereis Echo
Echo:/bin/echo/usr/share/man/man1/echo.1.gz
Attention

Whether we use the shell as true or false, we do not specify the full path of the execution program. If this program is in the context of the path variable, we can execute. Of course it's okay to specify the full path if you like.

You can also insist on specifying executable as the program you want to execute, and then args does not set the program. Although I don't see a clear document, I can do this on my computer:

>>> subprocess. Popen ([' 1 ', ' 2 ', ' 3 '], Shell=false, executable= ' echo ')
2 3
<subprocess. Popen Object at 0xb776f56c>
Not using the shell directly can lead to the inability to intuitively use redirects, pipelines, here documents, shell parameters, or other tricks that can be used at the command line. Next we'll look at how to use these features.
From standard output and error redirection
When you use Popen to execute the program, the output is usually sent to stdout, which is why you can see the content.

When you want to try to read standard output information from a program, you need to set the STDOUT parameter before calling Popen. The value to set is subprocess. PIPE:

Subprocess. PIPE

You can specify parameters for standard input, standard output, and standard error output for Popen, and it is important to note that the standard output stream needs to be open and writable.

Here's an example:

>>> process = subprocess. Popen ([' Echo ', ' Hello world! '], Shell=false, stdout=subprocess. PIPE)
To read the output from the pipe Thecommunicate () method:

In order to get the output from the pipeline, you can use the communicate () method:

>>> Print process.communicate ()
(' Hello world!\n ', None)
The return value of communicate () is a tuple, the first value is the data for the standard output, and the second output is the content of the standard error output.
Here's a script that lets us test the performance behavior of standard output and standard error output, and save it as test1.py:
Import Sys
Sys.stdout.write (' Message to stdout\n ')
Sys.stderr.write (' Message to stderr\n ')
Execute it:
>>> process = subprocess. Popen ([' Python ', ' test1.py '], Shell=false, stdout=subprocess. PIPE)
Message to StdErr
>>> Print process.communicate ()
(' Message to stdout\n ', None)
Note that the standard error output is printed after it has been generated, and the standard output is piped. This is because we have only set the standard output of the pipeline, let us also set the standard error output.
>>> process = subprocess. Popen ([' Python ', ' test1.py '], Shell=false, stdout=subprocess. PIPE, Stderr=subprocess. PIPE)
>>> Print process.communicate ()
(' Message to stdout\n ', ' message to stderr\n ')
This time the standard output and standard error output are captured by Python.

Now all the messages can be printed, and if we call communicate () again, we get an error message:

>>> Print process.communicate ()
Traceback (most recent):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.5/subprocess.py", line 668, in communicate
return Self._communicate (Input)
File "/usr/lib/python2.5/subprocess.py", line 1207, in _communicate
Rlist, wlist, xlist = Select.select (Read_set, Write_set, [])
VALUEERROR:I/O operation on closed file
When the Communicate () method reads the standard output and the standard error output, it ends when the Terminator (EOF) is encountered.
REDIRECT stderr to stdout
If you want to redirect the error message to standard output, you only need to specify a special value for the stderr parameter: stderr=subprocess. StdOut can be.
Write standard input
Writing data into a process is similar to the one described earlier. In order to write data, you need to open a pipeline to standard input first. By setting the Popen parameter stdin=subproces. Pipe can be achieved.
For testing, let's write an additional program that only outputs received: and input data. It outputs a message before exiting. Call this test2.py:
Import Sys
input = Sys.stdin.read ()
Sys.stdout.write (' Received:%s '%input)
In order to send the message to the standard input, put the information you want to send as a parameter of communicate () input. Let's run up:
>>> process = subprocess. Popen ([' Python ', ' test2.py '], Shell=false, stdin=subprocess. PIPE)
>>> Print process.communicate (' How is '? ')
Received:how is you? (None, none)
Note that the information sent by test2.py is printed to standard output, followed by (none, none), because the standard output and standard error outputs do not have an output pipeline set.

You can specify the stdout=subprocess as you did before. Pipe and stderr=subprocess. Pipe to set the output piping.

Class file properties
Popen has the stdout and stderr properties so that data can be written as a file, while the StdIn property can read data like a file. You can use them to replace communicate (). Below we will see how to use them.
Read and write the same process
Here's an example of saving it as a test3.py:
Import Sys
While True:
input = Sys.stdin.readline ()
Sys.stdout.write (' Received:%s '%input)
Sys.stdout.flush ()
This program is also simple to respond to the received data, let's run it up:
>>> Import Time
>>> process = subprocess. Popen ([' Python ', ' test3.py '], Shell=false, stdin=subprocess. PIPE, Stdout=subprocess. PIPE)
>>> for I in range (5):
... process.stdin.write ('%d\n '% i)
.... Output = Process.stdout.readline ()
.. print output
... time.sleep (1)
...
received:0

Received:1

Received:2

Received:3

Received:4

>>>
A row is output every second.

You should now have all the knowledge you need to interact with the Shell through Python.

Gets the return value, poll (), and Wait ()
When a program exits, he returns a positive integer to indicate its exit status. 0 means "end successfully", non-zero means "abnormal end". Most systems require a return value of 0-127, and others are undefined results. Some systems have pre-defined error correspondence, but are generally not used. Unix programs typically use 2 as a command syntax error and 1 for other errors.
You can get the program return value through the Popen. ReturnCode property. Here's an example:
>>> process = subprocess. Popen ([' Echo ', ' Hello world! '], Shell=false)
>>> Process.poll ()
>>> Print Process.returncode
None
>>> Process.poll ()
0
>>> Print Process.returncode
0
This returncode is not set at the beginning, initially is the default of none, it will always be none of the methods that you know to call subprocess such as poll () and wait (). These methods will set the ReturnCode. So, if you want to know the return value, call poll (2881064151) and wait ().

The poll () and wait () methods differ very little:

Popen.poll (): Checks whether the child process has ended. and sets and returns the. ReturnCode property. Popen.wait (): Waits for the child process to end. and sets and returns the. ReturnCode property.

A convenient way
The Subprocess module also provides a number of convenient ways to make it easier to execute shell commands. I didn't try it all. (translator: means to let the reader dig himself?) )
Understanding SYS.ARGV
If you want to write a Python script that accepts command-line arguments, the command-line arguments are routed and sys.argv as arguments. Here's a small example to save it as a command.py.
#!/usr/bin/env python
if __name__ = = ' __main__ ':
Import Sys
Print "Executable:%s"%sys.argv[0]
For ARG in sys.argv[1:]:
Print "Arg:%s"%arg
The If __name__ = = ' __main__ ' line ensures that the code runs before it is executed, not when it is introduced. To execute permissions on this file:
1
$ chmod 755 command.py
Here are some examples of runtimes:
$ python command.py
Executable:command.py
$ python command.py arg1
Executable:command.py
Arg:arg1
$ python command.py arg1 arg2
Executable:command.py
Arg:arg1
Arg:arg2
Note that regardless of how the Python script executes, sys.argv[0] is always the name of the script. SYS.ARGV[1] and after arguments are parameters that are accepted by the command line. You can force the Python script to be used as a module import by using the parameter-M.
$ python-m Command
Executable:/home/james/desktop/command.py
$ python-m Command arg1
Executable:/home/james/desktop/command.py
Arg:arg1
$ python-m Command arg1 arg2
Executable:/home/james/desktop/command.py
Arg:arg1
Arg:arg2
As you can see, Python takes-M as part of the command, so ' sys.srgv[0 ' contains the full path of the script. Now let's do it directly:
$./command.py
Executable:./command.py
$./command.py Arg1
Executable:./command.py
Arg:arg1
$./command.py arg1 arg2
Executable:./command.py
Arg:arg1
Arg:arg2
See, Sys.argv[0] contains the name of the Python script, Sys.argv[1] and his brothers still look the same, including all kinds of parameters.
Expand Shell
Sometimes we use wildcards in the shell to set up a set of parameters, for example, we run in Bash:
$./command.py *.txt
You might think the output should be:
Executable:./command.py
ARG: *.txt
This is not the result you want. The output should depend on the number of. txt files in the current folder. The following results are performed:
Executable:./command.py
Arg:errors.txt
Arg:new.txt
Arg:output.txt
Bash automatically expands the \*.txt to all the. TXT-compliant parameters. So the parameters received will exceed your expectations.

You can turn off the Shell interpretation feature by holding the arguments in quotation marks, but as long as you use them, you will realize that this is a very useful feature in most cases.

$./command.py "*.txt"
Executable:./command.py
ARG: *.txt

The Subprocess module also provides a number of convenient ways to execute shell commands

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.