- 論壇徽章:
- 0
|
要求是這樣的:
1) 登入mysql服務(wù)器(mysql -h localhost -uroot -p1234)。
2) 輸入mysql內(nèi)部命令show databases,如果返回的內(nèi)容出現(xiàn)mysql(存在mysql DB)就立刻強制退出整個python程序。
(關(guān)于要求2的解釋,假如show databases的返回內(nèi)容是information_schema \r\n mysql \r\n test。不要等到test出現(xiàn),馬上就退出或者殺死該程序)
我認為只有用subprocess能夠比較好的完成以上功能,所以以下都是以使用subprocess為前提。
個人試了好多方法,都不成功。
方法1:把stdout放到線程里
- def stdout_theard(p_stdout):
- time.sleep(0.01)
- for i in range(3000):
- print p_stdout.readline()
- s_command = 'mysql -h localhost -uroot -p1234'
- sub_process = subprocess.Popen(command , stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.PIPE, shell = True)
- thread_read_output = threading.Thread(target=stdout_theard, args=(sub_process.stdout,))
- thread_read_output.setDaemon('True')
- thread_read_output.start()
- sub_process.stdin.write('show databases;\r\n')
復(fù)制代碼
方法2:把stdout重定向到文件里
- s_command = 'mysql -h localhost -uroot -p1234'
- f_out = tempfile.TemporaryFile(mode='w+')
- f_err = tempfile.TemporaryFile(mode='w+')
- sub_process = subprocess.Popen(command , stdin = subprocess.PIPE, stdout = f_out, stderr = f_err, shell = True)
復(fù)制代碼 或者:
- os.dup2(sub_process.stdout.fileno(), f_out.fileno())
復(fù)制代碼
以上方法都沒成功。
希望前輩高手們指點。
|
|