Python 用一个脚本来控制另一个脚本的运行、关闭

版权声明:本文为博主原创文章,转载请注明来源 https://blog.csdn.net/qq_26948675/article/details/88545737

1、一开始按照网上教程,使用subprocess来实现另外一个脚本的运行和关闭,但是这个脚本在连续运行的时候不容易返回数据,判断脚本运行的状态

2、使用笨方法,用os.system运行脚本,使用os.kill(pid)杀死进程的方法关闭脚本的运行,这样就可以实现在一个脚本里面控制其他脚本的开启和运行了。当前这个方法在linux系统,如ubuntu18.04中跑,不存在问题

代码样例:

需要运行的脚本---run.py


import time
count=0
con=True
while con:
    now time=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
    count+=1
    print(count,now_time)
    time.sleep(1)

写的控制运行脚本的脚本代码---control.py

import os,signal
import time

def get_now_time():
    # 获取当前的本地时间
    now_time=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
    return now_time

def kill(pid):
    print('pid',pid)
    # pgid=os.getpgid(pid)
    # print(pgid)
    # a = os.killpg(pgid,signal.SIGKILL)
    a = os.kill(pid,signal.SIGKILL)
    print('已杀死pid为%s的进程, 返回值是:%s' % (pid, a))

def kill_target(target):
    cmd_run="ps aux | grep {}".format(target)
    out=os.popen(cmd_run).read()
    for line in out.splitlines():
        print(line)
        if '另外判断杀死进行所在的路径' in line:
            pid = int(line.split()[1])
            kill(pid)
# 建议在运行命令后面加上&符号,似乎是以另一个线程跑
os.system('python ./run.py &') 
       
while True:
    # 关闭
    if some_condition:
        print('暂停')
        kill_target('run.py')
    # 打开
    if some_else_condition:
        os.system('python ./run.py &')

猜你喜欢

转载自blog.csdn.net/qq_26948675/article/details/88545737
今日推荐