简体   繁体   中英

(Python) Blocking sub-process

I have a script class that queries from a database and displays the result. the problem is when i add a sub process below the script, the script hangs (or waits, and will continue if terminate with ctr-c)

eg. Group A will run if Group B is deleted. Group B will run if Group A is deleted

#Group A
queryStrings = ['SELECT top 100 * FROM myDb', 
'SELECT top 10 * FROM anotherDb']

## class that connects to db and output the content ## 
db = Database
conn = db.connectToDb()

for query in queryStrings:
     db.runPreQueries(conn, query)

conn.close

##Group B 

if os.path.exists("DoSomething.vbs"):
    p = subprocess.Popen("cscript DoSomething.vbs", stdout=subprocess.PIPE, stdin=subprocess.PIPE, shell=True)
    stdout, stderr = p.communicate()

print("vbs completed")

I also tried using subprocess.call, and then terminating it. This wont hang but it doesn't execute the script

p = subprocess.call("cscript DoSomething.vbs")
p.terminate()

when running conn.close you're not really closing the database. It does nothing because you're not calling the function.

So next call stays blocked waiting for database access.

Fix:

conn.close()

note that the proper way of running your process afterwards is (since you don't care about input, output, ...):

subprocess.check_call(["cscript","DoSomething.vbs"])

this will just fail if cscript returns a non-zero return code, which is safe enough.

Note that your database interface probably supports context manager, in that case, it would be better to write:

with db.connectToDb() as conn:    
    for query in queryStrings:
         db.runPreQueries(conn, query)

in that case, connection is closed automatically when exiting the with block.

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