Python exec 命令
最后修改于 2024 年 1 月 29 日
Python exec 教程展示了如何在 Python 中执行 shell 命令和程序。
在 Python 中,有几种方法可以执行 shell 命令或程序。我们可以使用 os 模块或 subprocess 模块。
subprocess 模块拥有执行命令的最强大的工具。
使用 os.system 的 Python exec 命令
os.system 是一个执行程序的简单工具。
simple.py
#!/usr/bin/python
import os
os.system('firefox')
该示例启动 Firefox。
使用 os.popen 的 Python exec 命令
os.popen 允许我们接收来自已执行命令的输入。它打开一个到命令的管道或从命令的管道。返回值是一个连接到管道的打开文件对象,该对象可以根据模式是 'r'(默认)还是 'w' 进行读取或写入。
read_output.py
#!/usr/bin/python
import os
output = os.popen('ls -la').read()
print(output)
在示例中,我们读取 ls 命令的输出并将其打印到控制台。
$ ./read_output.py total 28 drwxr-xr-x 2 janbodnar janbodnar 4096 Oct 11 14:30 . drwxr-xr-x 113 janbodnar janbodnar 4096 Oct 11 13:35 .. -rwxr-xr-x 1 janbodnar janbodnar 202 Oct 11 14:02 listing.py -rwxr-xr-x 1 janbodnar janbodnar 218 Oct 11 13:54 node_version.py -rwxr-xr-x 1 janbodnar janbodnar 547 Oct 11 14:04 pinging.py -rwxr-xr-x 1 janbodnar janbodnar 78 Oct 11 13:39 read_output.py -rwxr-xr-x 1 janbodnar janbodnar 50 Oct 11 13:37 simple.py
使用 subprocess 的 Python exec 命令
subprocess 模块允许我们创建新进程,连接到它们的输入/输出/错误管道,并获取它们的返回码。该模块旨在取代几个较旧的模块和函数。
node_version.py
#!/usr/bin/python
import subprocess
output = subprocess.run(['node', '--version'], text=True, capture_output=True)
print(f'Node version: {output.stdout.strip()}')
该示例使用 subprocess 模块获取 Node 的版本。
output = subprocess.run(['node', '--version'], text=True, capture_output=True)
run 执行命令,等待命令完成,并返回一个 CompletedProcess 实例。要捕获标准输出和标准错误输出,我们将 capture_output 设置为 true。默认情况下,输出以字节字符串形式返回。通过将 text 选项设置为 True,我们可以得到一个普通字符串。
$ ./node_version.py Node version: v12.18.4
使用 subprocess 列出 Python 目录内容
在以下示例中,我们列出用户主目录的内容。
listing.py
#!/usr/bin/python
import subprocess
from pathlib import Path
output = subprocess.Popen(['ls', '-l', Path.home()], text=True,
stdout=subprocess.PIPE)
stdout, _ = output.communicate()
print(stdout)
该模块中底层的进程创建和管理由 Popen 类处理。它比便利函数提供了更大的灵活性。
stdout, _ = output.communicate()
我们使用 communicate 方法与进程进行交互。它将数据发送到 stdin 并从 stdout 和 stderr 读取数据,直到到达 EOF。
来源
在本文中,我们执行了 shell 命令和程序。
作者
列出所有 Python 教程。