3种python调用其他脚本的方法

yipeiwu_com6年前Python基础

1.用python调用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')

另外一个python脚本b.py如下:

#!/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

2.python调用shell方法os.system()

#!/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@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

3.python调用shell方法os.popen()

#!/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.system.popen() 这个方法会打开一个管道,返回结果是一个连接管道的文件对象,该文件对象的操作方法同open(),可以从该文件对象中读取返回结果。如果执行成功,不会返回状态码,如果执行失败,则会将错误信息输出到stdout,并返回一个空字符串。这里官方也表示subprocess模块已经实现了更为强大的subprocess.Popen()方法。

总结

以上所述是小编给大家介绍的3种python调用其他脚本的方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对【听图阁-专注于Python设计】网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

相关文章

Python进阶学习之特殊方法实例详析

前言 最近在学习python,学习到了一个之前没接触过的--特殊方法。 什么是特殊方法?当我们在设计一个类的时候,python中有一个用于初始化的方法$__init__$,类似于java...

使用Flask-Cache缓存实现给Flask提速的方法详解

本文实例讲述了使用Flask-Cache缓存实现给Flask提速的方法。分享给大家供大家参考,具体如下: Django里面可以很方便的应用缓存,那Flask里面没准备这么周全怎么办?自己...

对python中dict和json的区别详解

1、json 和 字典 区别 >>>import json >>>json.dumps({1:2}) >>>'{"1":2}...

python中计算一个列表中连续相同的元素个数方法

最简单的例子: a = [1,1,1,1,2,2,2,3,3,1,1,1,3] # 问:计算a中最多有几个连续的1 很明显,答案是4 如果用代码实现,最先想到的就是itertool...

详解tensorflow训练自己的数据集实现CNN图像分类

详解tensorflow训练自己的数据集实现CNN图像分类

利用卷积神经网络训练图像数据分为以下几个步骤 1.读取图片文件 2.产生用于训练的批次 3.定义训练的模型(包括初始化参数,卷积、池化层等参数、网络) 4.训练 1 读取图片文件...