1. Detailed explanation
It is a function introduced in Python 3.5 and above to run child processes. It is part of the subprocess module and provides an easier and more powerful way to create and manage child processes. Functions can replace old functions such as , and .
The following is a detailed explanation of the function:
1.1. Basic usage
import subprocess result = (['ls', '-l'])
In this example, the ls -l command is executed and the command is waiting for the command to complete.
1.2. Detailed explanation of parameters
- args: The command to be executed and its parameters. Can be a string or a list of strings.
- stdin, stdout, stderr: represents standard input, standard output and standard error respectively. Can be , file object or file descriptor.
- input: input data passed to the child process.
- timeout: The timeout time (in seconds) of the child process. If the child process does not complete within the specified time, an exception will be thrown.
- check: If set to True and the child process returns a non-zero exit status code, an exception will be thrown.
- encoding: If encoding is specified, stdin, stdout, stderr will be decoded as a string.
- errors: Used to specify how to handle decoding errors.
- shell: If set to True, the command will be executed through the shell.
- cwd: Sets the current working directory of the child process.
- env: The environment variable used to specify the child process.
1.3. Return value
Returns a CompletedProcess object with the following properties:
- args: The executed command and its parameters.
- returncode: The exit status code of the child process.
- stdout: Standard output of the child process (if the stdout parameter is set to ).
- stderr: Standard error for child processes (if the stderr parameter is set to ).
1.4. Example
Capture output
result = (['ls', '-l'], stdout=, stderr=, text=True) print()
Handling errors
try: result = (['ls', '-l', '/nonexistent'], check=True) except as e: print(f"Error: {e}")
Use timeout
try: result = (['sleep', '10'], timeout=5) except as e: print(f"Timeout: {e}")
Execute commands through shell
result = ('echo $HOME', shell=True, text=True) print()
1.5. Summary
Provides a flexible and powerful way to execute a child process, and can control the behavior of the child process and process its output through various parameters. By using these parameters reasonably, most child process management needs can be met.
2. Execute python files
In Python, you can use . to execute another Python file. It is a function recommended in Python 3.5 and above for running child processes. Here is an example showing how to execute another Python file using :
Suppose you have a Python file called script_to_run.py and you want to run it from another Python script.
1. Create a file named script_to_run.py and write some code in it, such as:
# script_to_run.py print("Hello from script_to_run.py!")
2. Create another Python file, such as main_script.py, and use it to execute script_to_run.py:
# main_script.py import subprocess # Execute script_to_run.py using Python interpreterresult = (['python', 'script_to_run.py'], capture_output=True, text=True) # Print the output of the child processprint("Output of script_to_run.py:") print() # Print the error output of the child process (if any)if : print("Errors:") print()
In this example, the parameters of the function are explained as follows:
- ['python', 'script_to_run.py']: This is a list containing commands and parameters to be executed. Here we use the python interpreter to run the script_to_run.py file.
- capture_output=True: This parameter tells the capture of the standard output and standard error of the child process.
- text=True: This parameter tells you to return the output and error as a string instead of a byte.
Runmain_script.py, you should see the following output:
Output of script_to_run.py: Hello from script_to_run.py!
ifscript_to_run.py There are any error outputs in it, and they will also be captured and printed.
Note that if you are using Python 3.6 or later, you can use the check=True parameter to automatically check the child process's return code and raise an exception when the child process returns a non-zero status code:
# main_script.py import subprocess try: result = (['python', 'script_to_run.py'], capture_output=True, text=True, check=True) print("Output of script_to_run.py:") print() except as e: print("Errors:") print()
This makes it easier to handle child process execution failures.
This is the end of this article about the implementation example of python. For more related python content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!