(Python) 阻塞子进程
(Python) Blocking sub-process
我有一个脚本 class 从数据库查询并显示结果。问题是当我在脚本下面添加一个子进程时,脚本挂起(或等待,如果用 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
return 是一个足够安全的非零 return 代码,这将失败。
请注意,您的数据库接口可能支持上下文管理器,在这种情况下,最好这样写:
with db.connectToDb() as conn:
for query in queryStrings:
db.runPreQueries(conn, query)
在这种情况下,连接会在退出 with
块时自动关闭。
我有一个脚本 class 从数据库查询并显示结果。问题是当我在脚本下面添加一个子进程时,脚本挂起(或等待,如果用 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
return 是一个足够安全的非零 return 代码,这将失败。
请注意,您的数据库接口可能支持上下文管理器,在这种情况下,最好这样写:
with db.connectToDb() as conn:
for query in queryStrings:
db.runPreQueries(conn, query)
在这种情况下,连接会在退出 with
块时自动关闭。