How to run a Python script in a Linux system and get the results
When using a Linux system to develop and run Python scripts, we often need to run a script and get its results operation result. This article will introduce how to run a Python script in a Linux system and obtain its output. Below are the specific steps and sample code.
# sum.py def sum_numbers(a, b): return a + b result = sum_numbers(5, 3) print("The sum is:", result)
Save and close the file.
chmod +x sum.py
./sum.py
You will see the following output:
The sum is: 8
In this way, you will successfully Run the Python script on the Linux system and obtain the results.
# execute_script.py import subprocess script_output = subprocess.check_output(["./sum.py"]).decode("utf-8") print("Script output:", script_output)
In this example, first import the subprocess module, and then use the check_output function to run the script and get its output. Note that we use the decode function to convert the output from a byte stream to a string and print it out.
Save and close the file.
python execute_script.py
You will see the following Output result:
Script output: The sum is: 8
In this way, you have successfully run the Python script in the Linux system and obtained its output through the child process.
Summary:
In a Linux system, we can run a Python script and obtain its output in simple steps. First, we need to add executable permissions to the script. You can then run the script directly in the terminal and view the output. If you want to save the output results to a variable, you can use the check_output function of the subprocess module subprocess to accomplish this. I hope this article can help you use Python scripts to run and obtain results in Linux systems.
The above is the detailed content of How to run Python script in Linux system and get the results. For more information, please follow other related articles on the PHP Chinese website!