Home Backend Development Python Tutorial Summary of 3 ways to execute commands in python

Summary of 3 ways to execute commands in python

Nov 07, 2016 pm 04:42 PM

Currently, there are three ways I use to execute cmd in python:

1. Use os.system("cmd")

The characteristic is that when executed, the program will print out the information that cmd is executed on Linux.

import os
os.system("ls")
Copy after login

2. Use the Popen module to generate a new process

Most people now like to use Popen. The Popen method does not print out information about cmd execution on Linux. Indeed, Popen is very powerful and supports a variety of parameters and modes. Before use, you need from subprocess import Popen, PIPE. But the Popen function has a flaw, that is, it is a blocking method. If a lot of content is generated when running cmd, the function can easily get blocked. The solution is not to use the wait() method, but the return value of the execution cannot be obtained.

Popen prototype is:

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)

Parameter bufsize: Specify buffer.

The parameter executable is used to specify the executable program. Generally, we use the args parameter to set the program to be run. If the shell parameter is set to True, executable specifies the shell used by the program. Under the Windows platform, the default shell is specified by the COMSPEC environment variable.

The parameters stdin, stdout, and stderr represent the standard input, output, and error handles of the program respectively. They can be PIPE, file descriptors or file objects, or can be set to None to inherit from the parent process.

The parameter preexec_fn is only valid on Unix platforms and is used to specify a callable object that will be called before the child process runs.

Parameter Close_sfs: Under the Windows platform, if close_fds is set to True, the newly created child process will not inherit the input, output, and error pipes of the parent process. We cannot set close_fds to True and redirect the standard input, output, and error (stdin, stdout, stderr) of the child process.

If the parameter shell is set to true, the program will be executed through the shell.

The parameter cwd is used to set the current directory of the child process.

The parameter env is a dictionary type, used to specify the environment variables of the child process. If env = None, the child process's environment variables will be inherited from the parent process.

Parameter Universal_newlines: Under different operating systems, the line breaks of text are different. For example: '/r/n' is used to indicate replacement under Windows, while '/n' is used under Linux. If this parameter is set to True, Python will treat these newline characters as '/n'.

The parameters startupinfo and createionflags are only effective under windows. They will be passed to the underlying CreateProcess() function to set some attributes of the child process, such as: the appearance of the main window, the priority of the process, etc.

subprocess.PIPE

When creating a Popen object, subprocess.PIPE can initialize the stdin, stdout or stderr parameters, representing the standard stream for communication with the subprocess.

subprocess.STDOUT

When creating a Popen object, it is used to initialize the stderr parameter, indicating that errors will be output through the standard output stream.

Popen method:

Popen.poll()

is used to check whether the child process has ended. Sets and returns the returncode attribute.

Popen.wait()

Wait for the child process to end. Sets and returns the returncode attribute.

Popen.communicate(input=None)

Interact with the child process. Send data to stdin, or read data from stdout and stderr. The optional parameter input specifies parameters to be sent to the child process. Communicate() returns a tuple: (stdoutdata, stderrdata). Note: If you want to send data to the process through its stdin, the stdin parameter must be set to PIPE when creating the Popen object. Likewise, if you want to get data from stdout and stderr, you must set stdout and stderr to PIPE.

Popen.send_signal(signal)

Sends a signal to the child process.

Popen.terminate()

Stop the child process. Under the Windows platform, this method will call Windows API TerminateProcess() to end the child process.

Popen.kill()

Kill the child process.

Popen.stdin

If the parameter stdin is set to PIPE when creating a Popen object, Popen.stdin will return a file object for the child process to send instructions. Otherwise, None is returned.

Popen.stdout

If the parameter stdout is set to PIPE when creating a Popen object, Popen.stdout will return a file object for the child process to send instructions. Otherwise, None is returned.

Popen.stderr

If the parameter stdout is set to PIPE when creating a Popen object, Popen.stdout will return a file object for the child process to send instructions. Otherwise, None is returned.

Popen.pid

Get the process ID of the child process.

Popen.returncode

Get the return value of the process. If the process has not ended, return None.

For example:

p = Popen("cp -rf a/* b/", shell=True, stdout=PIPE, stderr=PIPE)  
p.wait()  
if p.returncode != 0:  
   print "Error."  
   return -1
Copy after login

3. Use the commands.getstatusoutput method

This method will not print out the information about cmd execution on Linux. The only advantage of this method is that it is not a blocking method. That is, there is no problem of Popen function blocking. Import commands are required before use.

For example:

status, output = commands.getstatusoutput("ls")
Copy after login

There is also a method to get only output and status:

commands.getoutput("ls")  
commands.getstatus("ls")
Copy after login


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Python vs. JavaScript: Community, Libraries, and Resources Python vs. JavaScript: Community, Libraries, and Resources Apr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Python: Automation, Scripting, and Task Management Python: Automation, Scripting, and Task Management Apr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

What is vscode What is vscode for? What is vscode What is vscode for? Apr 15, 2025 pm 06:45 PM

VS Code is the full name Visual Studio Code, which is a free and open source cross-platform code editor and development environment developed by Microsoft. It supports a wide range of programming languages ​​and provides syntax highlighting, code automatic completion, code snippets and smart prompts to improve development efficiency. Through a rich extension ecosystem, users can add extensions to specific needs and languages, such as debuggers, code formatting tools, and Git integrations. VS Code also includes an intuitive debugger that helps quickly find and resolve bugs in your code.

Can visual studio code run python Can visual studio code run python Apr 15, 2025 pm 08:00 PM

VS Code not only can run Python, but also provides powerful functions, including: automatically identifying Python files after installing Python extensions, providing functions such as code completion, syntax highlighting, and debugging. Relying on the installed Python environment, extensions act as bridge connection editing and Python environment. The debugging functions include setting breakpoints, step-by-step debugging, viewing variable values, and improving debugging efficiency. The integrated terminal supports running complex commands such as unit testing and package management. Supports extended configuration and enhances features such as code formatting, analysis and version control.

See all articles