(Python)阻塞子进程

2024-05-15 03:48:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个脚本类,它从数据库中查询并显示结果。问题是,当我在脚本下面添加一个子进程时,脚本挂起(或者等待,如果用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")

我也试过用子流程调用,然后终止它。它不会挂起,但不会执行脚本

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

Tags: from脚本dbtopstdoutgroupconnquery
1条回答
网友
1楼 · 发布于 2024-05-15 03:48:38

运行conn.close时,并不是真的关闭数据库。它什么也不做,因为你没有调用函数。你知道吗

所以下一个呼叫被阻塞,等待数据库访问。你知道吗

修正:

conn.close()

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

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

如果cscript返回一个足够安全的非零返回码,那么这将失败。你知道吗

请注意,您的数据库接口可能支持context manager,在这种情况下,最好编写:

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

在这种情况下,当退出with块时,连接将自动关闭。你知道吗

相关问题 更多 >

    热门问题