Python调用外部脚本的三种实现方式:os.system与os.popen详解

Noah
Noah
发布时间:2026-10-13 | 3人浏览过
原创

本文详细介绍在Python中调用其他脚本的两种常用方法:os.system()与os.popen()。通过Python调用Python脚本及Shell脚本的实例,对比两者在返回值、执行状态码获取及输出处理上的差异。os.system直接执行并返回状态码,而os.popen打开管道返回文件对象,虽功能受限但可读取输出,官方推荐使用subprocess模块替代。

Python调用外部脚本概述

在Python开发中,经常需要调用外部的Python脚本或Shell命令来执行特定任务。本文将通过具体实例,演示如何使用Python调用另一个Python脚本,以及如何通过不同方式执行Shell脚本。

调用Python脚本实例


#!/usr/local/bin/python3.7
import time
import os 

count = 0
str = ('python b.py')
result1 = os.system(str)
print(result1)
while True:
  count = count + 1
  if count == 8:
   print('this count is:',count) 
   break
  else:
   time.sleep(1)
   print('this count is:',count)  

print('Good Bye')

假设存在一个名为b.py的Python脚本,其内容如下:

#!/usr/local/bin/python3.7 print('hello world')

执行上述调用后,终端输出的结果如下所示:

[python@master2 while]$ python a.py hello world this count is: 1 this count is: 2 this count is: 3 this count is: 4 this count is: 5 this count is: 6 this count is: 7 this count is: 8 Good Bye

接下来介绍使用os.system()方法调用Shell脚本的方式。

使用os.system调用Shell脚本


#!/usr/local/bin/python3.7
import time
import os 

count = 0
n = os.system('sh b.sh')
while True:
  count = count + 1
  if count == 8:
   print('this count is:',count) 
   break
  else:
   time.sleep(1)
   print('this count is:',count)  

print('Good Bye')

对应的Shell脚本内容如下:

#!/bin/sh echo "hello world"

运行该Python脚本后的终端输出结果如下:

[python@master2 while]$ python a.py hello world this count is: 1 this count is: 2 this count is: 3 this count is: 4 this count is: 5 this count is: 6 this count is: 7 this count is: 8 Good Bye

第三种方法是使用os.popen()来调用Shell脚本。

使用os.popen调用Shell脚本及对比


#!/usr/local/bin/python3.7
import time
import os 
count = 0
n = os.system('sh b.sh')
while True:
  count = count + 1
  if count == 8:
   print('this count is:',count) 
   break
  else:
   time.sleep(1)
   print('this count is:',count)  

print('Good Bye')

该方法的运行结果如下:

[python@master2 while]$ python a.py <os._wrap_close object at 0x7f7f89377940> ['hello world\n'] this count is: 1 this count is: 2 this count is: 3 this count is: 4 this count is: 5 this count is: 6 this count is: 7 this count is: 8 Good Bye

os.popen()方法会打开一个管道,并返回一个连接该管道的文件对象。该文件对象的操作方式与open()函数类似,可以从其中读取执行结果。需要注意的是,如果命令执行成功,该方法不会返回状态码;如果执行失败,错误信息会被输出到stdout,且返回值为空字符串。官方文档指出,subprocess模块中提供的subprocess.Popen()方法已实现了更强大的功能,建议优先使用。

以上内容总结了Python调用外部脚本的基本方法,希望能为读者提供实用的参考。

相关标签:

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表