Subprocess executes linux commands in batches in python
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
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
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 'exit 1' returned non-zero exit status 1
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'Hello World!\n' >>> 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 'exit 1' returned non-zero exit status 1##subprocess.Popen(...) Used to execute complex system commands
Parameters:
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.
>>> 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>
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='/tmp/',) >>> 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)
>>> 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) ('1\n2\n', '')
>>> obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) >>> out_error_list = obj.communicate('print("hello")') >>> print(out_error_list) ('hello\n', '')
Related recommendations:
Use python to execute shell scripts and dynamically transfer parameters and basic use of subprocess Introduction and use of the subprocess moduleDetailed introduction to the Python standard library subprocess subprocess packageThe 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!

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Choosing Python or C depends on project requirements: 1) If you need rapid development, data processing and prototype design, choose Python; 2) If you need high performance, low latency and close hardware control, choose C.

By investing 2 hours of Python learning every day, you can effectively improve your programming skills. 1. Learn new knowledge: read documents or watch tutorials. 2. Practice: Write code and complete exercises. 3. Review: Consolidate the content you have learned. 4. Project practice: Apply what you have learned in actual projects. Such a structured learning plan can help you systematically master Python and achieve career goals.

Methods to learn Python efficiently within two hours include: 1. Review the basic knowledge and ensure that you are familiar with Python installation and basic syntax; 2. Understand the core concepts of Python, such as variables, lists, functions, etc.; 3. Master basic and advanced usage by using examples; 4. Learn common errors and debugging techniques; 5. Apply performance optimization and best practices, such as using list comprehensions and following the PEP8 style guide.

Python is suitable for beginners and data science, and C is suitable for system programming and game development. 1. Python is simple and easy to use, suitable for data science and web development. 2.C provides high performance and control, suitable for game development and system programming. The choice should be based on project needs and personal interests.

Python is more suitable for data science and rapid development, while C is more suitable for high performance and system programming. 1. Python syntax is concise and easy to learn, suitable for data processing and scientific computing. 2.C has complex syntax but excellent performance and is often used in game development and system programming.

It is feasible to invest two hours a day to learn Python. 1. Learn new knowledge: Learn new concepts in one hour, such as lists and dictionaries. 2. Practice and exercises: Use one hour to perform programming exercises, such as writing small programs. Through reasonable planning and perseverance, you can master the core concepts of Python in a short time.

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.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Dreamweaver CS6
Visual web development tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.