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中词典的values值的修改或新增KEY详解

对python中词典的values值的修改或新增KEY详解

在python中,对词典的值,可以新增,或者修改,如下: 以上这篇对python中词典的values值的修改或新增KEY详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望...

python执行外部程序的常用方法小结

本文实例总结了python执行外部程序的常用方法。分享给大家供大家参考。具体分析如下: 在python中我们可以通过下面的方法直接调用系统命令或者外部程序,使用方便 1、os模块的exe...

Python3 venv搭建轻量级虚拟环境的步骤(图文)

Python3 venv搭建轻量级虚拟环境的步骤(图文)

今天先聊一聊在windows/mac iOS系统下用venv搭建python轻量级虚拟环境的问题。 使用venv搭建的虚拟环境同virtualenv搭建的虚拟环境,即venv可替代vir...

tensorflow 固定部分参数训练,只训练部分参数的实例

在使用tensorflow来训练一个模型的时候,有时候需要依靠验证集来判断模型是否已经过拟合,是否需要停止训练。 1.首先想到的是用tf.placeholder()载入不同的数据来进行计...

Python计算库numpy进行方差/标准方差/样本标准方差/协方差的计算

使用numpy可以做很多事情,在这篇文章中简单介绍一下如何使用numpy进行方差/标准方差/样本标准方差/协方差的计算。 variance: 方差 方差(Variance)是概率论中最基...