📅  最后修改于: 2023-12-03 14:46:04.188000             🧑  作者: Mango
If you are a programmer or system administrator, then you might have encountered situations where you need to spawn a new shell from within your Python code. This can usually be achieve using the subprocess
module in Python.
In this article, we will discuss how to spawn a new shell from Python code, and execute commands within it.
The subprocess
module in Python provides a range of functions for working with subprocesses, including spawning new processes and working with their input and output streams.
To spawn a new shell process, we can use the subprocess.Popen()
function. This function takes a command-line argument as input, which is the command that we want to execute in the new shell.
Here is an example:
import subprocess
# Spawn a new shell and print its output
process = subprocess.Popen('bash', stdout=subprocess.PIPE)
output = process.communicate()[0]
print(output)
In this example, we use the Popen()
function to spawn a new bash
shell process. We also redirect the shell's output to a PIPE
, so that we can read its output later. Finally, we call the communicate()
function to wait for the shell process to exit, and read its output.
Once we have spawned a new shell process, we can execute commands within it by passing them as strings to the communicate()
function.
Here is an example:
import subprocess
# Spawn a new shell and execute a command
process = subprocess.Popen('bash', stdin=subprocess.PIPE, stdout=subprocess.PIPE)
output = process.communicate(input=b"echo 'Hello, World!'\n")[0]
print(output)
In this example, we use the Popen()
function to spawn a new bash
shell process, and redirect its input and output streams to PIPE
s. We then pass a command to the shell process by writing it to its input stream using the communicate()
function. Finally, we read the output of the shell process and print it.
In this article, we discussed how to spawn a new shell process from Python code, and how to execute commands within it. The subprocess
module provides a flexible and powerful way of working with subprocesses, and should be your go-to choice for most subprocess-related tasks in Python.