Python调用其他脚本

2023-03-21  本文已影响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())
上一篇 下一篇

猜你喜欢

热点阅读