python 进程的开启与关闭

进程开启

import os
from multiprocessing import Process

Process(target=main, name="keyname").start()

// main 为封装的函数,进程需要执行的程序

在封装的函数中(即上述main())里面获取进程标记pid

pid = os.getpid()

进程的关闭:通过pid进行关闭

os.system('taskkill /f /im %s' % pid)

例如

这是需要执行的程序,封装成main()函数,并将该进程的pid写入txt文件,方便关闭

def main():
    print("Air爬虫启动")
    pid = os.getpid()
    print("pid:", pid)
    with open("./data/air_pid.txt", "w") as f:
        f.write(str(pid))
    result = get_idx()
    # print(len(idx))
    idx = get_idx()
    # print(len(idx))
    for i in idx:
        url = f'https://api.waqi.info/api/attsse/{i}/yd.json'
        with open('./data/url.txt', 'r', encoding='utf-8') as f:
            line = f.read().splitlines()
        if url not in line:
            try:
                encryption_list = get_py_json(url)
                decode_data = get_decode_data(encryption_list)
                data_list1, city = get_index_data(decode_data)
                print(city)
                write_file(city, data_list1)
                with open('./data/url.txt', 'a', encoding='utf-8') as f:
                    f.write(f'{url}\n')
            except Exception as e:
                print(f"请求错误:{e}")
                time.sleep(5)
        # time.sleep(random.randint(1,10))

这是开启与关闭进程,通过前端输入值判断是开启还是关闭

# 搜索
@app.route('/')
def search():
    city = request.args.get("city")
    if city:
        session['city'] = city
        return redirect(url_for("index"))
    Air = request.args.get("Air")
    if Air == 'yes':
        Process(target=main, name="keyname").start()
    if Air == 'no':
        with open('./data/air_pid.txt', 'r') as f:
            pid = f.read()
        os.system('taskkill /f /im %s' % pid)
        print("Air爬虫终止")

你可能感兴趣的:(python,开发语言,爬虫,进程,flask)