Home Backend Development Python Tutorial Subprocess executes linux commands in batches in python

Subprocess executes linux commands in batches in python

Apr 27, 2018 am 11:55 AM
linux python subprocess

This article explains in detail how to use subprocess to execute Linux commands in batches in python. Friends who are interested can refer to it.

The relevant modules and functions that can execute shell commands are:

  • os.system

  • os.spawn

  • os.popen --Abandoned

  • popen --Abandoned

  • commands --Abandoned, 3. Removed from

subprocess

call

##Execute the command and return the status code

>>> import subprocess
>>> ret = subprocess.call(["ls", "-l"], shell=False)
total 4684
-rw-r--r-- 1 root root   454 May 5 12:20 aa.py
-rw-r--r-- 1 root root    0 May 8 16:51 aa.txt
-rw-r--r-- 1 root root 4783286 Apr 11 16:39 DockerToolbox.exe
-rw-r--r-- 1 root root   422 May 5 12:20 ip_info.txt
-rw-r--r-- 1 root root   718 Apr 19 10:52 my.cnf
>>> ret = subprocess.call("ls -l", shell=True)
total 4684
-rw-r--r-- 1 root root   454 May 5 12:20 aa.py
-rw-r--r-- 1 root root    0 May 8 16:51 aa.txt
-rw-r--r-- 1 root root 4783286 Apr 11 16:39 DockerToolbox.exe
-rw-r--r-- 1 root root   422 May 5 12:20 ip_info.txt
-rw-r--r-- 1 root root   718 Apr 19 10:52 my.cnf
>>> print(ret)
0
Copy after login

check_call

Execute the command, if the execution status code is 0, return 0, otherwise an exception will be thrown

>>> subprocess.check_call(["ls", "-l"])
total 4684
-rw-r--r-- 1 root root   454 May 5 12:20 aa.py
-rw-r--r-- 1 root root    0 May 8 16:51 aa.txt
-rw-r--r-- 1 root root 4783286 Apr 11 16:39 DockerToolbox.exe
-rw-r--r-- 1 root root   422 May 5 12:20 ip_info.txt
-rw-r--r-- 1 root root   718 Apr 19 10:52 my.cnf
0
>>> subprocess.check_call("exit 1", shell=True)
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
 File "/usr/local/python3.5/lib/python3.5/subprocess.py", line 581, in check_call
  raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: Command &#39;exit 1&#39; returned non-zero exit status 1
Copy after login

check_output

Execute the command, if the status code is 0, return the execution result, otherwise throw an exception

>>> subprocess.check_output(["echo", "Hello World!"])
b&#39;Hello World!\n&#39;
>>> subprocess.check_output("exit 1", shell=True)
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
 File "/usr/local/python3.5/lib/python3.5/subprocess.py", line 626, in check_output
  **kwargs).stdout
 File "/usr/local/python3.5/lib/python3.5/subprocess.py", line 708, in run
  output=stdout, stderr=stderr)
subprocess.CalledProcessError: Command &#39;exit 1&#39; returned non-zero exit status 1
Copy after login

##subprocess.Popen(...)

Used to execute complex system commands

Parameters:

args: shell command, can be a string or sequence type (such as: list, tuple)


bufsize: Specify the buffer. 0 no buffering, 1 line buffering, other buffer sizes, negative system buffering

stdin, stdout, stderr: represent the standard input, output, and error handles of the program respectively

preexec_fn: Only valid under Unix platform, used to specify a executable object (callable object), which will be called before the child process runs

close_sfs: Under Windows platform, if close_fds If set to True, the newly created child process will not inherit the input, output, and error pipes of the parent process.

So you cannot set close_fds to True and redirect the standard input, output and error (stdin, stdout, stderr) of the child process at the same time.

shell: Same as above

cwd: used to set the current directory of the child process

env: used to specify the environment variable of the child process . If env = None, the child process's environment variables will be inherited from the parent process.

universal_newlines: Different systems have different line breaks, True -> Agree to use n

startupinfo and createionflags are only valid under windows

Will be passed to the underlying CreateProcess() function to set some properties of the child process, such as: the appearance of the main window, the priority of the process, etc.

Execute ordinary commands


>>> import subprocess
>>> ret1 = subprocess.Popen(["mkdir","t1"])
>>> ret2 = subprocess.Popen("mkdir t2", shell=True)
>>> print(ret1)
<subprocess.Popen object at 0x7f4d7609dd30>
>>> print(ret2)
<subprocess.Popen object at 0x7f4d7609dc18>
Copy after login

There are two types of commands entered in the terminal:

Enter to get the output, such as: ifconfig

    Enter a certain environment, depend on it and then enter it, such as: python
  • >>> import subprocess
    >>> obj = subprocess.Popen("mkdir t3", shell=True, cwd=&#39;/tmp/&#39;,)
    >>> import subprocess
    >>> obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
    >>> obj.stdin.write("print(1)\n")
    9
    >>> obj.stdin.write("print(2)")
    8
    >>> obj.stdin.close()
    >>> cmd_out = obj.stdout.read()
    >>> obj.stdout.close()
    >>> cmd_error = obj.stderr.read()
    >>> obj.stderr.close()
    >>> print(cmd_out)
    1
    2
    >>> print(cmd_error)
    Copy after login

>>> import subprocess
>>> 
>>> obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
>>> obj.stdin.write("print(1)\n")
9
>>> obj.stdin.write("print(2)")
8
>>> 
>>> out_error_list = obj.communicate()
>>> print(out_error_list)
(&#39;1\n2\n&#39;, &#39;&#39;)
Copy after login

>>> obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
>>> out_error_list = obj.communicate(&#39;print("hello")&#39;)
>>> print(out_error_list)
(&#39;hello\n&#39;, &#39;&#39;)
Copy after login

Related recommendations:

Use python to execute shell scripts and dynamically transfer parameters and basic use of subprocess

Introduction and use of the subprocess module

Detailed introduction to the Python standard library subprocess subprocess package

The above is the detailed content of Subprocess executes linux commands in batches 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

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)

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Linux Architecture: Unveiling the 5 Basic Components Linux Architecture: Unveiling the 5 Basic Components Apr 20, 2025 am 12:04 AM

The five basic components of the Linux system are: 1. Kernel, 2. System library, 3. System utilities, 4. Graphical user interface, 5. Applications. The kernel manages hardware resources, the system library provides precompiled functions, system utilities are used for system management, the GUI provides visual interaction, and applications use these components to implement functions.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

How to check the warehouse address of git How to check the warehouse address of git Apr 17, 2025 pm 01:54 PM

To view the Git repository address, perform the following steps: 1. Open the command line and navigate to the repository directory; 2. Run the "git remote -v" command; 3. View the repository name in the output and its corresponding address.

Golang vs. Python: Performance and Scalability Golang vs. Python: Performance and Scalability Apr 19, 2025 am 12:18 AM

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Python vs. C  : Learning Curves and Ease of Use Python vs. C : Learning Curves and Ease of Use Apr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Golang vs. Python: Key Differences and Similarities Golang vs. Python: Key Differences and Similarities Apr 17, 2025 am 12:15 AM

Golang and Python each have their own advantages: Golang is suitable for high performance and concurrent programming, while Python is suitable for data science and web development. Golang is known for its concurrency model and efficient performance, while Python is known for its concise syntax and rich library ecosystem.

See all articles