Python executes shell external commands

Source: Internet
Author: User

1, Os.system ()
External programs executed by this method will output the results directly to standard output. Os.system The return result for executing shell $? Value.
Therefore, it is appropriate to use this method when executing programs that do not have output results. such as Touch, rm a file, and so on.

In [1]: Import Osin [2]: Os.system (' Touch test.txt ') out[2]: 0In [3]: Os.system (' rm-rf test.txt ') out[3]: 0


2, Os.popen ()
This method combines the characteristics of os.system and files. Can solve the disadvantage that os.system can't get the result of program execution
Os.popen returns something similar to a file handle. You can do something similar to the operation of the file on the returned result.

In [6]: output = Os.popen (' cat/etc/passwd ') in [7]: For line in Output.readlines (): ...: Print Line.strip () ...: root:x:0:0:root:/root:/bin/bashdaemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologinbin:x:2:2:bin:/bin:/usr/sbin/ nologinsys:x:3:3:sys:/dev:/usr/sbin/nologinsync:x:4:65534:sync:/bin:/bin/syncgames:x:5:60:games:/usr/games:/ Usr/sbin/nologin

can help (output) to get assistance to manipulate this output


3. Commands Module
This module provides three main methods:
(1), GetOutput (CMD)
Return output (stdout or stderr) of executing cmd in a shell.
Returns the standard output or error output of a shell command

in [+]: commands.getoutput (' ls/home-l ') out[17]: ' Total 4\ndrwxr-xr-x to admin admin 4096 5\xe6\x9c\x88 3 09:48 admin ' In []: Commands.getoutput (' ls/homeaaa-l ') out[18]: ' ls:cannot access/homeaaa:no such file or directory '


(2), GetStatus (file)
Return output of "Ls-ld <file>" in a string.
Gets the status of a file. Equivalent to executing the ls-ld file

in [+]: commands.getstatus ('/bin/ls ') out[25]: '-rwxr-xr-x 1 root root 110080 3\xe6\x9c\x88 '//equivalent to execute L S-ld/bin/lsin [+]: Os.system (' Ls-ld/bin/ls ')-rwxr-xr-x 1 root root 110080 March 2014/bin/ls


(3), Getstatusoutput (CMD)
Return (status, output) of executing cmd in a shell.
Returns the Shell's status code and output results

In [St]: commands.getstatusoutput (' ls/home-l ') out[20]: (0, ' total 4\ndrwxr-xr-x to admin admin 4096 5\xe6\x9c\x88 3 09 : + Admin ') in [+]: commands.getstatusoutput (' ls/homeaa-l ') out[21]: (+, ' ls:cannot access/homeaa:no such file or di Rectory ')


4, subprocess related modules.
It can be seen from the help of this module. One of its main purposes is to replace the functions of Os.system, os.spawn*, os.popen*, popen2.*, and commands.* modules.


A very powerful class Popen in the Subproces module, our main learning focus should be on this
Class Popen (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: Can be a string or a sequence (list | tuple). Actually the string is also a sequence AH. Oh, we are here to tell the sequence that the list and the tuple. In the case of a sequence, the first element is an executable command

In Unix systems, Shell=ture and Shell=false (the default) and the args parameter have some influence on the relationship.

Take a look at the following:
Subprocess. Popen (["Cat", "/etc/passwd"])
Subprocess. Popen ("cat/etc/passwd")
Let's see if these two types of notation are OK

In []: subprocess. Popen (["Cat", "/etc/passwd"]) Root:x:0:0:root:/root:/bin/bashdaemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologinbin: X:2:2:bin:/bin:/usr/sbin/nologinsys:x:3:3:sys:/dev:/usr/sbin/nologinsync:x:4:65534:sync:/bin:/bin/syncin [30]: Subprocess.                                   Popen ("cat/etc/passwd")---------------------------------------------------------------------------OSError Traceback (most recent)


The first one is OK. The second way is not OK. What is the reason for this?
Main time Shell=false (default) This parameter does the ghost.

In Unix, Shell=false is subprocess. Popen () uses OS.EXECVP () to execute the subroutine of the response.
When args is a string, Popen considers the string to be the first element in the sequence (the executable program).

Call OS.EXECVP (), to the $path to find the executable program, not found, so the program has an exception.
But this is also ordered, if written as follows:
Subprocess. Popen ("/bin/pwd")

in [+]: subprocess. Popen ("/bin/pwd")/home/dexin/python/tcollector

None of this is going to matter.

But just to make subprocess. Popen ("cat/etc/passwd") can be executed correctly, what should be done? Set Shell=true. So that when you execute a similar program, the appropriate shell is called to do the Shell-c "CAT/ETC/PASSWD"

Subprocess. Popen ("cat/etc/passwd", Shell=true) out[33]: <subprocess. Popen at 0x7f922a6b2350>in [+]: root:x:0:0:root:/root:/bin/bashdaemon:x:1:1:daemon:/usr/sbin:/usr/sbin/ nologinbin:x:2:2:bin:/bin:/usr/sbin/nologinsys:x:3:3:sys:/dev:/usr/sbin/nologinsync:x:4:65534:sync:/bin:/bin/ Syncgames:x:5:60:games:/usr/games:/usr/sbin/nologinman:x:6:12:man:/var/cache/man:/usr/sbin/nologinlp:x:7:7:lp :/var/spool/lpd:/usr/sbin/nologinmail:x:8:8:mail:/var/mail:/usr/sbin/nologinnews:x:9:9:news:/var/spool/news:/ Usr/sbin/nologinuucp:x:10:10:uucp:/var/spool/uucp:/usr/sbin/nologin


This article is from the "Learning Notes" blog, so be sure to keep this source http://unixman.blog.51cto.com/10163040/1641396

Python executes shell external commands

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.