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中实现同行输入/接收多个数据的示例

在python中实现同行输入/接收多个数据的示例

在使用python去AC题时总会遇到这样的问题,题目要求同行输入一组数据,但是你使用input时却不能做到,导致不断的CE,这个时候怎么样来解决的这个问题呢? 很简单,只需要使用inpu...

使用pytorch实现可视化中间层的结果

使用pytorch实现可视化中间层的结果

摘要 一直比较想知道图片经过卷积之后中间层的结果,于是使用pytorch写了一个脚本查看,先看效果 这是原图,随便从网上下载的一张大概224*224大小的图片,如下 网络介绍 我们使用...

使用pycharm生成代码模板的实例

通过在File->setting->File and Code Templates设置模板代码,这样就可以在新建python文件的时候自动带上抬头。 # -*- codi...

python+jinja2实现接口数据批量生成工具

python+jinja2实现接口数据批量生成工具

在做接口测试的时候,我们经常会遇到一种情况就是要对接口的参数进行各种可能的校验,手动修改很麻烦,尤其是那些接口参数有几十个甚至更多的,有没有一种方法可以批量的对指定参数做生成处理呢。 答...

理解Python中的绝对路径和相对路径

本文介绍了Python中的绝对路劲和相对路径,分享给大家,也给自己留个笔记 1、绝对路径 os.path.abspath("文件名"): 显示的是一个文件的绝对路劲 eg:...