简体   繁体   English

(Python)阻止子流程

[英](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) 问题是当我在脚本下面添加子进程时,脚本挂起(或等待,如果以ctr-c终止,它将继续)

eg. 例如。 Group A will run if Group B is deleted. 如果删除了组B,则将运行组A。 Group B will run if Group A is deleted 如果删除了A组,则B组将运行

#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. 我也尝试使用subprocess.call,然后终止它。 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. 当运行conn.close您并没有真正关闭数据库。 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. 如果cscript返回一个非零的返回码(足够安全),这将失败。

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. 在这种情况下,退出with块时将自动关闭连接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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