2017-09-07 42 views
0

我想在一個循環中調用一個函數,該循環發送一個mysql查詢得到該行的狀態。然後在循環中,如果狀態是5,則打破循環。功能不被稱爲循環 - Python

狀態從網頁上的一個按鈕被更改,這意味着取消作業。 php腳本嚴格地將MYSQL數據庫更新爲5,但在python腳本中只將其視爲0. 0是默認值,這意味着作業正在運行或正在等待運行。

任何人都可以找出爲什麼我的函數(docheck)保持變量檢查值爲0而不是運行並從數據庫中獲得數字5。

import pysftp 
import pexpect 
import sys 
import MySQLdb 
import os 
from pexpect import pxssh 

# Establish a MySQL connection 
con = MySQLdb.connect (host="localhost", user = "root", passwd = "R42chlA!", db = "BT") 

def getTest_Cases(): 
    cur = con.cursor() 
    cur.execute("Select * from Test_Cases") 
    row = cur.fetchall() 
    if row is not None: 
     return row 
    else: 
     return None 

def getNextComputeID(): 
    cur = con.cursor() 
    cur.execute("Select job_ID from Compute_jobs where status = 0 order by created_time ASC limit 1") 
    row = cur.fetchone() 
    if row is not None: 
     return row[0] 
    else: 
     return None 

def getNextFile(): 
    cur = con.cursor() 
    cur.execute("Select sheet from Compute_jobs where job_ID = '%s' order by created_time ASC limit 1" %jobid) 
    row = cur.fetchone() 
    if row is not None: 
     return row[0] 
    else: 
     return None 

def getRowsinOutTable(): 
    cur = con.cursor() 
    cur.execute("SELECT COUNT(*) FROM %s_output;" %tablename) 
    row = cur.fetchone() 
    if row is not None: 
     return row[0] 
    else: 
     return None 

def docheck(): 
    cur = con.cursor() 
    cur.execute("Select status from Compute_jobs where job_ID = \"%s\" order by created_time ASC limit 1" %jobid) 
    row = cur.fetchone() 
    if row is not None: 
     return row[0] 
    else: 
     return None 

jobid = getNextComputeID() 
filename = getNextFile() 
tablename = filename[:-3] 

srv = pysftp.Connection(host="10.52.117.175", username="root", password="[password]") 
srv.put("caseid/%s" %filename, "/home/enduser/%s" %filename) 
srv.close() 

ssh = pxssh.pxssh() 
ssh.login('10.52.117.175', 'root', '[password]') 
fout = file('logs/%s_%s.txt' % (tablename, jobid),'w') 
ssh.logfile = fout 
ssh.sendline("cd /home/enduser/") 
ssh.expect("enduser") 
ssh.sendline("./run_jobs %s" %filename) 
while True: 
    try: 
     ssh.expect("\n") 
     output = ssh.before 
     output = output.strip() 
     output = output.replace("\"", "'") 
     print(output) 
     checked = docheck() 
     print(checked) 
     print(jobid) 
     print "-----------------------------------------------------------------" 
     if checked == "5": 
      print "job cancelled!" 
      ssh.close 
      break 
    except: 
     ssh.close  
     break 


checked = docheck() 
print(checked) 
print(docheck()) 
ssh.close  
+0

你的意思是變量'checked'(你說「檢查」)? – cdarke

+0

是的,但功能是docheck –

+0

我可以建議你在'docheck()'函數中跟蹤'row'(所有的,不只是第一個元素)的值嗎?我們無法嘗試您的代碼來重現問題。 – cdarke

回答

0

break只會導致退出循環,因此循環後的任何語句都會被執行。 另一方面,return會導致當前函數退出,因此不會執行此函數內部的其他語句。

所以 - 如果您想在找到第一個元素後退出當前函數,請使用 return。 如果您想繼續執行此功能,請使用break

順便說一句我沒有看到你的代碼上的任何地方+1。那麼它如何將每次都添加到5?