简体   繁体   中英

Python close children subprocess

I have a very simple question on killing child subprocesses in scripts written in python 3.

Where,

If I have,

my_process = None

def open_storage():
    my_process = subprocess.Popen("waffles.exe")

def kill_children():
    my_process.kill()

After calling open_storage() , if I call kill_children() , I get

AttributeError: 'NoneType' object has no attribute 'kill'

But if I have,

my_process = None

my_process = subprocess.Popen("waffles.exe")

def kill_children():
    my_process.kill()

Everything works fine.

Can anyone explain this strange behaviour? I need to have open_storage() as a function because it's designed to be triggered by a tkinter button.

Thanks.

You need to use global, otherwise it will use a local variable.

def open_storage():
    global my_process
    my_process = subprocess.Popen("waffles.exe")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM