gpt4 book ai didi

python - (Python) 阻塞子进程

转载 作者:太空宇宙 更新时间:2023-11-04 00:27:43 24 4
gpt4 key购买 nike

我有一个从数据库查询并显示结果的脚本类。问题是当我在脚本下面添加一个子进程时,脚本挂起(或等待,如果用 ctr-c 终止将继续)

例如。如果删除 B 组,A 组将运行。如果删除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")

我还尝试使用 subprocess.call,然后终止它。这不会挂起,但不会执行脚本

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

最佳答案

当运行 conn.close 时,您并没有真正关闭数据库。它什么都不做,因为您没有调用该函数。

因此下一次调用将保持阻塞状态,等待数据库访问。

修复:

conn.close()

请注意,之后运行流程的正确方法是(因为您不关心输入、输出...):

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

如果 cscript 返回非零返回码,这将失败,这是足够安全的。

请注意,您的数据库接口(interface)可能支持上下文管理器,在这种情况下,最好这样写:

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

在这种情况下,连接会在退出 with block 时自动关闭。

关于python - (Python) 阻塞子进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46893428/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com