在 Python 中执行 BASH 命令——在同一进程中

在 Python 中执行 BASH 命令——在同一进程中
在Python中执行BASH命令,可以使用`os.system()`或`subprocess`模块。以下是两种方法的详细步骤:

方法一:使用 `os.system()`

```python
import os

# 执行一个bash命令,例如显示当前目录下的所有文件
command = "ls"
output = os.system(command)

print("Command output: ", output)
```

这里,`os.system()`函数接收一个字符串参数,这个参数是BASH命令。然后它会执行这个命令,并返回命令的退出状态(通常为0表示成功,非0表示失败)。如果命令的输出需要捕获,可以使用`subprocess`模块。

方法二:使用 `subprocess`

```python
import subprocess

# 执行一个bash命令,例如显示当前目录下的所有文件
command = "ls"
output = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

print("Command output: ", output.stdout.decode('utf-8'))
```

这里,`subprocess.run()`函数接收几个参数。第一个参数是要执行的命令。`shell=True`表示使用shell来执行这个命令,这是必要的,因为Python默认不会解析shell命令。`stdout=subprocess.PIPE`和`stderr=subprocess.PIPE`表示我们想要捕获命令的输出和错误。然后我们可以通过`.stdout.decode('utf-8')`来获取命令的输出。

测试用例:

```python
import os
import subprocess

# 测试os.system()函数
command = "ls"
output = os.system(command)
print("Testing os.system(): ", output == 0, command, "exited with", output)

# 测试subprocess.run()函数
command = "ls"
output = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).stdout.decode('utf-8')
print("Testing subprocess.run(): ", output)

# 测试os.system()函数,并捕获输出
command = "ls -l"
output = os.popen(command).read().strip()
print("Testing os.popen(): ", output)

# 测试subprocess.PIPE
command = "echo hello"
output = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).stdout.decode('utf-8')
print("Testing subprocess.PIPE: ", output)

# 测试bash环境变量
command = "echo $PATH"
output = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).stdout.decode('utf-8')
print("Testing bash environment variables: ", output)
```

应用场景和示例:

假设你正在开发一个Python程序,需要获取系统信息或者执行一些shell命令。你可以使用上述方法在Python中调用BASH命令。例如,如果你想要查看当前的用户,可以使用`whoami`命令,或者获取当前的工作目录,可以使用`pwd`命令。如果你想修改环境变量,可以使用`export`命令。

作者:潮易

物联沃分享整理
物联沃-IOTWORD物联网 » 在 Python 中执行 BASH 命令——在同一进程中

发表回复