我正在使用Ubuntu配对在Raspberry上运行Google Cloud SQL Proxy,但是目前,我必须打开一个终端来启动代理,而另一个终端则运行我的python SQL脚本。我需要自动化这个过程。
要启动代理我运行:
cd my_proxy_dir
sudo ./cloud_sql_proxy -dir=./ -instance_name -credential_file=./key_file.json
输出的最后一行是
准备连接
█(方块闪烁,终端被阻塞,代理拥有终端)
在第二个终端,我运行我的python脚本,其中包含一个到云实例的MySQL连接,第一个终端的输出报告新连接,在我的python脚本结束时,连接也被通知:
(时间戳)准备连接...
(时间戳)新连接......
(时间戳)连接已完成...
█(方块闪烁,终端被阻塞,代理拥有终端)
现在,因为我正在使用python,所以我创建了一个线程,因为我无法在不阻塞的情况下运行代理启动命令。这是我的运行方法:
my_thread...
def run(self)
subprocess.call(['sudo', './proxy/cloud_sql_proxy', '-dir=./proxy/', '-instances=instance_name','-credential_file=./proxy/key_file.json', '&'])
print('pass')
在用thread.terminate()
终止线程之前,它永远不会打印“pass”那我做什么
my_proxy_thread = Thread_proxy()
my_proxy_thread.start()
time.sleep(10) #because I don't know when the proxy socket has bee created so I only wait
# Once created the socket
do_my_mysql_stuff()
my_proxy_thread.terminate() # kill the thread and also the proxy socket in the bad way
它工作,我的代理套接字创建,my_sql工作正常,但我无法控制代理输出,我不知道发生了什么,如果它失败或关闭,工作...我不能发送关闭套接字的指令。由于子进程命令输出
,我在终端中弄得一团糟我需要什么?
感谢所有人:)
答案 0 :(得分:0)
subprocess.call
将直接将参数传递给没有中间shell的进程。 &
是shell的一部分,因此您需要设置Shell=true
才能正确解释它。