Home Backend Development Python Tutorial Summarize several methods of executing commands in python

Summarize several methods of executing commands in python

Sep 04, 2017 pm 12:00 PM
python Order implement

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

1. Use os.system("cmd")

The characteristic is that the program will type cmd during execution. Information executed on linux.

import os

os.system("ls")

2. Use the Popen module to generate a new process

Now most people 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 newlines 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. wait.

subprocess.PIPE

When creating a Popen object, subprocess.PIPE can initialize the stdin, stdout or stderr parameters to represent 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()

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)

Send a signal to the child process.

Popen.terminate()

Stop (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 the 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 the Popen object, Popen.stdout will return a file object for the child process to send instructions. Otherwise, None is returned.

Popen.stderr

If the stdout parameter is set to PIPE when the Popen object is created, 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

3. Use commands.getstatusoutput method

This method will not print out 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")

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

commands. getoutput("ls")

commands.getstatus("ls")

The above is the detailed content of Summarize several methods of executing commands in python. For more information, please follow other related articles on the PHP Chinese website!

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Do mysql need to pay Do mysql need to pay Apr 08, 2025 pm 05:36 PM

MySQL has a free community version and a paid enterprise version. The community version can be used and modified for free, but the support is limited and is suitable for applications with low stability requirements and strong technical capabilities. The Enterprise Edition provides comprehensive commercial support for applications that require a stable, reliable, high-performance database and willing to pay for support. Factors considered when choosing a version include application criticality, budgeting, and technical skills. There is no perfect option, only the most suitable option, and you need to choose carefully according to the specific situation.

How to use mysql after installation How to use mysql after installation Apr 08, 2025 am 11:48 AM

The article introduces the operation of MySQL database. First, you need to install a MySQL client, such as MySQLWorkbench or command line client. 1. Use the mysql-uroot-p command to connect to the server and log in with the root account password; 2. Use CREATEDATABASE to create a database, and USE select a database; 3. Use CREATETABLE to create a table, define fields and data types; 4. Use INSERTINTO to insert data, query data, update data by UPDATE, and delete data by DELETE. Only by mastering these steps, learning to deal with common problems and optimizing database performance can you use MySQL efficiently.

Navicat's method to view MongoDB database password Navicat's method to view MongoDB database password Apr 08, 2025 pm 09:39 PM

It is impossible to view MongoDB password directly through Navicat because it is stored as hash values. How to retrieve lost passwords: 1. Reset passwords; 2. Check configuration files (may contain hash values); 3. Check codes (may hardcode passwords).

Does mysql need the internet Does mysql need the internet Apr 08, 2025 pm 02:18 PM

MySQL can run without network connections for basic data storage and management. However, network connection is required for interaction with other systems, remote access, or using advanced features such as replication and clustering. Additionally, security measures (such as firewalls), performance optimization (choose the right network connection), and data backup are critical to connecting to the Internet.

How to optimize MySQL performance for high-load applications? How to optimize MySQL performance for high-load applications? Apr 08, 2025 pm 06:03 PM

MySQL database performance optimization guide In resource-intensive applications, MySQL database plays a crucial role and is responsible for managing massive transactions. However, as the scale of application expands, database performance bottlenecks often become a constraint. This article will explore a series of effective MySQL performance optimization strategies to ensure that your application remains efficient and responsive under high loads. We will combine actual cases to explain in-depth key technologies such as indexing, query optimization, database design and caching. 1. Database architecture design and optimized database architecture is the cornerstone of MySQL performance optimization. Here are some core principles: Selecting the right data type and selecting the smallest data type that meets the needs can not only save storage space, but also improve data processing speed.

HadiDB: A lightweight, horizontally scalable database in Python HadiDB: A lightweight, horizontally scalable database in Python Apr 08, 2025 pm 06:12 PM

HadiDB: A lightweight, high-level scalable Python database HadiDB (hadidb) is a lightweight database written in Python, with a high level of scalability. Install HadiDB using pip installation: pipinstallhadidb User Management Create user: createuser() method to create a new user. The authentication() method authenticates the user's identity. fromhadidb.operationimportuseruser_obj=user("admin","admin")user_obj.

Can mysql workbench connect to mariadb Can mysql workbench connect to mariadb Apr 08, 2025 pm 02:33 PM

MySQL Workbench can connect to MariaDB, provided that the configuration is correct. First select "MariaDB" as the connector type. In the connection configuration, set HOST, PORT, USER, PASSWORD, and DATABASE correctly. When testing the connection, check that the MariaDB service is started, whether the username and password are correct, whether the port number is correct, whether the firewall allows connections, and whether the database exists. In advanced usage, use connection pooling technology to optimize performance. Common errors include insufficient permissions, network connection problems, etc. When debugging errors, carefully analyze error information and use debugging tools. Optimizing network configuration can improve performance

Does mysql need a server Does mysql need a server Apr 08, 2025 pm 02:12 PM

For production environments, a server is usually required to run MySQL, for reasons including performance, reliability, security, and scalability. Servers usually have more powerful hardware, redundant configurations and stricter security measures. For small, low-load applications, MySQL can be run on local machines, but resource consumption, security risks and maintenance costs need to be carefully considered. For greater reliability and security, MySQL should be deployed on cloud or other servers. Choosing the appropriate server configuration requires evaluation based on application load and data volume.

See all articles