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

yipeiwu_com5年前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线程安全及多进程多线程实现方法详解

进程和线程的区别 进程是对运行时程序的封装,是系统资源调度和分配的基本单位 线程是进程的子任务,cpu调度和分配的基本单位,实现进程内并发。 一个进程可以包含多个线程,线...

使用tensorflow实现AlexNet

使用tensorflow实现AlexNet

AlexNet是2012年ImageNet比赛的冠军,虽然过去了很长时间,但是作为深度学习中的经典模型,AlexNet不但有助于我们理解其中所使用的很多技巧,而且非常有助于提升我们使用深...

python利用Guetzli批量压缩图片

python利用Guetzli批量压缩图片

Google 又开源了,这次开源了一款图像算法工具 Guetzli。Guetzli,在瑞士德语中是“cookie(曲奇)”的意思,是一个针对数码图像和网页图像的 JPEG 编码器,能够通...

python实现列表中由数值查到索引的方法

python实现列表中由数值查到索引的方法

如下所示: 以上这篇python实现列表中由数值查到索引的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。...

python将txt等文件中的数据读为numpy数组的方法

实际中,很多数据都是存为txt文件、csv文件等,但是在程序中处理的时候numpy数组或列表是最方便的。本文简单介绍读入txt文件以及将之转化为numpy数组或列表的方法。 1 将txt...