美文网首页
Python调用其他脚本

Python调用其他脚本

作者: 顾北向南 | 来源:发表于2023-03-21 20:29 被阅读0次

Python调用python a.py脚本

# main.py
import time
import os 
count = 0
str = ('python a.py')
result = os.system(str)
print(result)
while True:
  count = count + 1
  if count == 5:
   print('this count is:',count) 
   break
  else:
   time.sleep(1)
   print('this count is:',count)  
# a.py
print('hello world')
  • 输出
> python main.py
hello world
this count is: 1
this count is: 2
this count is: 3
this count is: 4
this count is: 5

Python调用shell方法os.system()

# main.py
import time
import os 
count = 0
# 返回值是脚本的退出状态码
n = os.system('sh a.sh')
while True:
  count = count + 1
  if count == 5:
   print('this count is:',count) 
   break
  else:
   time.sleep(1)
   print('this count is:',count)  
# a.sh
echo "hello world"
  • 输出
> python main.py
hello world
this count is: 1
this count is: 2
this count is: 3
this count is: 4
this count is: 5

Python调用shell方法os.popen()

import os
if __name__ == "__main__":
    print("this is a test file ")
    cmd = "ls"
    # 返回值是脚本执行过程中的输出内容
    val = os.popen(cmd)
    print(val)
    print(val.read())
  • 像调用”ls”这样的shell命令,应该使用popen的方法来获得内容

相关文章

网友评论

      本文标题:Python调用其他脚本

      本文链接:https://www.haomeiwen.com/subject/khomrdtx.html