在Python程序中调用外部程序有多种方法,以下是几种常用的方式:
os.system 基本使用
```python
import os
exit_code = os.system('dir') Windows
exit_code = os.system('ls') Linux
```
带参数的命令:
```python
os.system('ping www.google.com')
```
错误处理:
```python
def run_command(command):
status = os.system(command)
if status != 0:
print(f"Command failed with exit code: {status}")
return status
```
subprocess.run 基本使用
```python
import subprocess
result = subprocess.run(['ls', '-l'], capture_output=True, text=True)
print(result.stdout)
```
错误处理:
```python
try:
result = subprocess.run(['ffmpeg', '-i', 'input.mp4', 'output.mp4'], check=True)
except subprocess.CalledProcessError as e:
print(f"Command failed with exit code: {e.returncode}")
print(f"Error output: {e.stderr}")
```
os.popen 基本使用
```python
import os
file_like = os.popen("adb devices")
print(file_like.read())
```
特点:
底层是`subprocess.Popen`
可获取子进程的标准输出
返回值为代表管道的文件对象
Runtime.getRuntime().exec() 基本使用
```java
Runtime.getRuntime().exec("notepad.exe");
```
特点:
可以与调用的程序进行交互
通过`Process`对象的`getInputStream()`, `getOutputStream()`, 和 `getErrorStream()` 方法获取输入输出流
System.Diagnostics.ProcessStartInfo 基本使用
```csharp
System.Diagnostics.ProcessStartInfo p = new ProcessStartInfo("nnnn.exe", "参数");
p.WorkingDirectory = exepath;
p.WindowStyle = ProcessWindowStyle.Hidden;
System.Diagnostics.Process Proc = System.Diagnostics.Process.Start(p);
```
特点:
可以设置外部程序的工作目录
可以控制窗口的显示方式
建议
推荐使用:`subprocess.run` 是现代Python开发中推荐的方式,因为它提供了更强大和灵活的功能,如捕获标准输出和错误流,以及更好的进程控制能力。
简单场景:对于简单的命令行操作,`os.system` 仍然是一个简单直接的选择。
交互需求:如果需要与外部程序进行交互,可以考虑使用 `Runtime.getRuntime().exec()` 或 `System.Diagnostics.ProcessStartInfo`。
根据具体需求和场景选择合适的方法,可以提高代码的健壮性和可维护性。