Common Methods for running system commands in python (full) and python commands

Source: Internet
Author: User

Common Methods for running system commands in python (full) and python commands

The details are as follows:

1 OS. system

For example, if you run the following command in ipython, the running status is returned.

OS. system ('cat/etc/passwdqc. conf ')
Min = disabled, 24, 11, 8, 7
Max = 40
Passphrase = 3
Match = 4
Similar = deny
Random = 47
Enforce = everyone
Retry = 3
Out [6]: 0

2 OS. popen ()

Popen (command [, mode = 'R' [, bufsize])-> pipe
Open a pipe to/from a command returning a file object.

Running returned results

In [20]: output = OS. popen ('cat/proc/cpuinfo ')
In [21]: lineLen = []
In [22]: for line in output. readlines ():
LineLen. append (len (line ))
....:
In [23]: line
Line lineLen
In [23]: lineLen
Out [23]:
[14,
25,
...

3. How to return results and running status at the same time, commands module:

#String form: <module 'commands' from '/usr/lib64/python2.7/commands.pyc'>File: /usr/lib64/python2.7/commands.pyDocstring:Execute shell commands via os.popen() and return status, output.Interface summary:import commandsouttext = commands.getoutput(cmd)(exitstatus, outtext) = commands.getstatusoutput(cmd)outtext = commands.getstatus(file) # returns output of "ls -ld file"A trailing newline is removed from the output string.Encapsulates the basic operation:pipe = os.popen('{ ' + cmd + '; } 2>&1', 'r')text = pipe.read()sts = pipe.close()

Commands example:

In [24]: (status, output) = commands. getstatusoutput ('cat/proc/cpuinfo ')
In [25]: status
Out [25]: 0
In [26]: len (output)
Out [26]: 3859

4. subprocess

Run in ipython "? Subprocess "It can be found that subprocess is a new module used by python to replace pipeline operation commands such as OS. popen ().

A more real-world example wowould look like this:

try:  retcode = call("mycmd" + " myarg", shell=True)  if retcode < 0:    print >>sys.stderr, "Child was terminated by signal", -retcode  else:    print >>sys.stderr, "Child returned", retcodeexcept OSError, e:  print >>sys.stderr, "Execution failed:", e

Compared with the preceding methods, subprocess is easy to control and monitor the running results of processes. subprocess provides multiple functions to meet different requirements of parent processes for sub-processes:

4.1.1 subprocess. call ()

The parent process of the parent process waits for the child process to complete and returns the exit code.

4.1.2 subprocess. check_call ()

The parent process waits for the child process to complete and returns 0. If the returncode is not 0, an error subprocess is thrown. calledProcessError, which contains the returncode attribute. try... else t... to check

4.1.3 subprocess. check_output ()

The parent process waits for the child process to complete.

Returns the output result of the sub-process to the standard output.

Check the exit information. If the returncode is not 0, an error subprocess is thrown. calledProcessError. This object contains the returncode attribute and output attribute. The output attribute is the output result of the standard output. try... else t... to check

For example:

In [32]: out = subprocess. call ("ls-l", shell = True)
Total 42244
-Rw-r --. 1 ****** 366 May 26 ChangeLog

4.2.1

The above three functions are all derived from the wapper (encapsulation) of the Popen () function. If you need more personalized applications, you need to use the popen () function.

After a Popen object is created, the main program does not automatically wait for the child process to complete. We must call the wait () method of the object before the parent process will wait (that is, block blocking)

[wenwt@localhost syntax]$ rm subprocess.pyc [wenwt@localhost syntax]$ python process.py parent process[wenwt@localhost syntax]$ PING www.google.com (173.194.219.99) 56(84) bytes of data.^C[wenwt@localhost syntax]$ --- www.google.com ping statistics ---5 packets transmitted, 0 received, 100% packet loss, time 3999ms

Add the wait method:

[wenwt@localhost syntax]$ python process.py PING www.google.com (173.194.219.103) 56(84) bytes of data.--- www.google.com ping statistics ---5 packets transmitted, 0 received, 100% packet loss, time 3999msparent process

The above content is all described in this article and I hope you will like it.

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.