Two Methods for executing shell in python: pythonshell

Source: Internet
Author: User
Tags pprint

Two Methods for executing shell in python: pythonshell

1. Use the built-in commands module of python to execute shell

Commands encapsulates Python OS. popen () and uses SHELL command strings as its parameters to return command result data and command execution status;

This command has been replaced by subprocess;

# Coding = UTF-8 ''' Created on August 1 @ author: crazyant.net ''' import commandsimport pprint def pai_exe (pai_string): print "will exe cmd, cmd:" + pai_string return commands. getstatusoutput (pai_string) if _ name __= = "_ main _": pprint. pprint (cmd_exe ("ls-la "))

Ii. Run shell Using python's latest subprocess Module

Python has abandoned OS. system, OS. spawn *, OS. popen *, popen2. *, commands. * to execute commands in other languages. subprocesss is a recommended method;

Subprocess allows you to create many sub-processes. When you create a sub-process, it refers to the input, output, and error output pipelines of the sub-process and sub-process. After execution, you can obtain the output results and execution status.

# Coding = UTF-8 ''' Created on August 1 @ author: crazyant.net ''' import shleximport datetimeimport subprocessimport time def execute_command (optional string, cwd = None, timeout = None, shell = False ): "" executing a SHELL command encapsulates the Popen method of subprocess, and supports timeout judgment. It supports reading stdout and stderr parameters: cwd: Changing the path when running the command. If it is set, the sub-process will directly change the current path to cwd timeout: time-out time, second, supports decimal, precision 0.1 second shell: whether to run Returns: return_code Raises: Exception through shell: execution timeout "if shell: Repeated string_list = repeated string else: Repeated string_list = shlex. split (distinct string) if timeout: end_time = datetime. datetime. now () + datetime. timedelta (seconds = timeout) # The media transcoding queue does not specify the standard output or error output. Therefore, the media transcoding queue is printed to the screen. sub = subprocess. popen (sort string_list, cwd = cwd, stdin = subprocess. PIPE, shell = shell, bufsize = 4096) # subprocess. poll () method: Check whether the sub-process is finished. If the sub-process is finished, set and return the code and place it in subprocess. while sub in the returncode variable. poll () is None: time. sleep (0.1) if timeout: if end_time <= datetime. datetime. now (): raise Exception ("Timeout: % s" % seconds string) return str (sub. returncode) if _ name __= = "_ main _": print execute_command ("ls ")

You can also specify stdin and stdout as a variable in Popen to directly receive the output variable value.

Summary

Sometimes SHELL execution in python is quite necessary. For example, different shell processes can be started using the Python thread mechanism. Currently, subprocess is the method officially recommended by Python and supports the most functions, we recommend that you use it.

Well, the above is all about this article. I hope this article will help you in your study or work. If you have any questions, please leave a message.

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.