3种python调用其他脚本的方法,你还知道其他的方法吗?
admin
2023-01-20 12:01:07
0

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()

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:579817333 
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
#!/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()

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:579817333 
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
#!/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 

['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()方法。

相关内容

热门资讯

美防长:对伊朗战争已耗资375... △美国国防部长赫格塞思(资料图)央视记者当地时间21日获悉,美国国防部长赫格塞思表示,美国对伊朗战争...
在全国抗议声中,泽连斯基解除乌... 据乌克兰媒体《基辅独立报》报道,乌克兰总统泽连斯基解除了乌克兰武装部队总司令瑟尔斯基的职务,并任命联...
也门胡塞武装:停靠沙特港口船只... 新华社科威特城7月21日电(记者尹炣)萨那消息:也门胡塞武装20日警告国际航运公司称,与沙特港口开展...
特朗普:胡塞武装若封锁红海,美... 新华社华盛顿7月21日电(记者黄强 徐剑梅)美国总统特朗普21日在白宫会见到访的黎巴嫩总统奥恩时表示...
AI第一城|GOAI世界人工智... 7月21日上午,GOAI世界人工智能开源大赛(Global Open-source AI Chall...
刀闸阀行业解读:申奥阀门的技术... 在工业流体控制领域,高粘度介质、强腐蚀环境以及含固体颗粒的复杂工况,长期是制约管路系统安全运行的关键...
原创 华... 现在的手机屏幕做得是越来越大了,iPhone17 Pro Max也做了6.9英寸大屏,国产自然不能输...
WAIC2026:没有花架子,... 齐鲁晚报·齐鲁壹点 记者 任磊磊 “逛不完,根本逛不完!”在世界人工智能大会展馆现场,不少观众一边逛...
欧洲议会外委会首次派团访华,王... 2026年7月21日,中共中央政治局委员、外交部长王毅在北京会见欧洲议会外事委员会主席麦克阿里斯特率...
大熊猫“福虎”嘴角生疮,官方回... 7月21日,南京紫清湖野生动物世界发布通告,称“福虎”自嘴角边长疮至今,园区一直在中国大熊猫保护研究...