Use python to execute linux commands and pythonlinux commands

Source: Internet
Author: User

Use python to execute linux commands and pythonlinux commands

Python version 2.7.12

1. Obtain the execution result of a linux Command. For example, obtain the process tree structure of a PID. the linux Command is pstree-p pid, which can be easily obtained by a module in python. As for the case where the obtained results are garbled sometimes, please refer to the previous article: some commonly used commands in ubuntu

Command iscommands.getoutput(Cmd),

cmd = "pstree -p %s"%pidresult = commands.getoutput(cmd)

 

 

2. Start a new process to execute the script file. You need to use another module in python. subprocess

Next, let's briefly describe the functions.

1subprocess.call(Args,*,Stdin = None,Stdout = None,Stderr = None,Shell = False) The Calling process will wait until the sub-process executes the args and then return the returncode.

2subprocess.check_output(Args,*,Stdin = None,Stderr = None,Shell = False,Universal_newlines = False) The Calling process waits for the sub-process to execute args and returns its output in byte string format. NOTE: If return code is a non-zero value,CalledProcessError exception,

 

  

To call commands in the form of sub-processes, you need to use the Popen class.

  subprocess.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)

By default, a sub-process is opened and is not blocked.

  

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.