Skip to main content
 首页 » 编程设计

python之os.system 可以启动但不能终止 Python 进程

2025年05月04日23mq0036

我无法使用 os.system() 阻止 python 脚本运行,但我可以使用 os.system() 使其运行。当我在终端上运行相同的命令来终止进程时,它起作用了。

我的 web_plants.py 脚本中有这段代码片段,可以使用 Flask 将其部署在 html 中:

@app.route("/auto/water/<toggle>") 
def auto_water(toggle): 
    running = False 
    if toggle == "ON": 
        templateData = template(text = "Auto Watering On") 
        for process in psutil.process_iter(): 
            try: 
                if process.cmdline()[1] == 'auto_water.py': 
                    templateData = template(text = "Already running") 
                    running = True 
            except: 
                pass 
        if not running: 
            os.system("python auto_water.py") 
    else: 
        templateData = template(text = "Auto Watering Off") 
        os.system("pkill -f water.py") 
 
    return render_template('main.html', **templateData) 
 
if __name__ == "__main__": 
    app.run(host='0.0.0.0', port=80, debug=True) 

我有一个 water.py 脚本,其中包含我 html 页面上按钮的 auto_water 函数。但该功能运行良好,所以我想这不是问题。

def auto_water(pump_pin = 38): 
    init_output(pump_pin) 
    print("Reading Soil Humidity values from ADS1115") 
 
    try: 
        while True: 
            m = adc.read_adc(0, gain=GAIN) 
            print('Moisture Level:{0:>6}'.format(m)) 
            time.sleep(1) 
            if m>23000:  
                #GPIO.output(pump_pin, GPIO.LOW) 
                print "relay on" 
            else: 
                #GPIO.output(pump_pin, GPIO.HIGH) 
                print "relay off" 
    except KeyboardInterrupt: 
        GPIO.cleanup() 
    except Exception as e: 
        print (e) 

我有这个 auto_water.py 文件,它导入 water 并调用 auto_water() 函数来运行它。使用此文件的目的是当我单击“停止”按钮时能够在文件运行时将其杀死。

import water 
 
#From the water.py script, call the auto_water function and run it as a process 
 
if __name__ == "__main__": 
    water.auto_water() 

脚本一直在运行,我必须从终端使用 sudo pkill -f water.py 终止它,以使其停止。但同样的命令在 web_plants.py 文件上不起作用,当我按下“停止”按钮时,我曾用它来停止它。但是,当我杀死它时,网页会注册它并显示文本“Auto Watering OFF”,如 web_plants.py 文件中的以下行所示:

templateData = template(text="Auto Watering Off") 
os.system("pkill -f water.py")  

请您参考如下方法:

你能用 os.kill() 代替吗?

import os 
import signal 
 
os.kill(pid, signal.SIGTERM) 

如果您没有可用的 pid,请使用 subprocess.check_output 获取它。 (如果您使用的是 Python 3.5+,请改用 subprocess.run。)

import os 
import signal 
import subprocess 
 
def get_water_pid(): 
    return int(subprocess.check_output(['pgrep', '-f', 'water.py']).strip()) 
 
def kill_water_process(): 
    pid = get_water_pid() 
    os.kill(pid, signal.SIGTERM)