Search code examples
pythonprocesssubprocesspopen

Check certain Popen is running at first (==Checking variable is assigned)


I got a running Thread p in a function and trying to check at first, whether it's already running or not

if p wasn't running it spits reference before the assignment error

from subprocess import check_output,Popen
from asyncio.subprocess import PIPE
from threading import Thread

def th():
    p= Popen([r'C:\Users\dow\Desktop\dd\StructuredOsuMemoryProviderTester.exe'],stdout=PIPE,stderr=PIPE) if p else 0
    for line in p.stdout:
        line=line.decode('utf-8')
        print(line)
while True:
    try:
        Thread(target=th).start()
//extra codes

What I've tried

  • p.poll()
    this gets NameError in the same way course

  • progs = str(check_output('tasklist'))
    checking if p is not in progs.

this have a problem briefly popping a black window with a brief delay at every checking loop

and if the process's name is long, it cuts the rest name so I think kindof unstable way

What is a good way to check whether p is running==assigned?


Solution

  • It looks like you want to run your exe exactly once from this program. To do that you could keep some global state to let you know whether the process has been executed. Wrap that state in a lock to avoid race conditions and your code could be:

    from subprocess import Popen, PIPE, STDOUT
    from threading import Thread, Lock
    
    exe_has_run = False
    exe_lock = Lock()
    
    def th():
        global exe_has_run
        with exe_lock:
            if primary := exe_has_run is False:
                exe_has_run = True
                p = Popen([r'C:\Users\dow\Desktop\dd\StructuredOsuMemoryProviderTester.exe'],stdout=PIPE,stderr=STDOUT)
        if primary:
            for line in p.stdout:
                line=line.decode('utf-8')
                print(line)
    
    
    while True:  # this will blow up your process
        Thread(target=th).start()
    //extra codes