2017-08-02 96 views
0

我对Python很新。我有一些代码使用Thread应停止,直到符合条件。等到条件满足为止

当我在控制台中按下键1脚本停止,而不是在条件test1 == 1:条件下运行的部分。

当条件满足时,我想运行脚本每个线程只有一次与现有的会话


代码:

def test() 

    #some code 
    test1 = 0 

    while (test1 == 1): #Wait until is set 1 in if __name__ == '__main__': and run the code only 1 time 
     response = session.get('https://www.example.com/') 


     opts = ChromeOptions() 
     opts.add_experimental_option("detach", True) 
     driver = Chrome(chrome_options=opts) 

     driver.get(response.url + '#/checkout/login') 
     print "Checking Out..." 
     test1+=1 

def Main(): 
     t1 = Thread(target=test, args=()) 
     t1.start() 


if __name__ == '__main__': 
    test = input('How many tasks you want to start? \n') 
    for i in range(test): 
     Main() 
    test1 = input('Proceed? if yes press 1 \n') 
+1

'测试1 = 0 ...而(test1的== 1):',循环永远不会运行,因为'test1'不等于1 –

+0

'while'并不意味着'wait' –

+0

在脚本的最后一行,你可以看到,我设置了test1 = 1,所以循环应该运行,然后 – Dking1199

回答

0

如果你想运行你的代码只有一次,那么你为什么用循环下去。 只需简单地指定没有循环的代码即可。

response = session.get('https://www.example.com/') 
opts = ChromeOptions() 
opts.add_experimental_option("detach", True) 
driver = Chrome(chrome_options=opts) 
driver.get(response.url + '#/checkout/login') 
print "Checking Out..." 
test1+=1 

否则您可以指定while语句类似。

While True: 
    // Logic 
    break # once logic finely executed, then break the loop 

While循环将执行给定的语句块,直到条件变为False。在你的情况下,虽然condition始终是False,所以在初始控制阶段本身,while块将被跳过。

+0

是的,但是当我运行没有循环的代码时,它只是运行没有任何条件。我想在它问我“你会继续吗?”之后运行它。并且我输入一个值,并且当循环记录条件时,那么代码应该在每个线程上运行一次,而现有会话是 – Dking1199

0
checker = 0 
    placeHolder = 0 


    def Main(): 
     global test 
     global checker 
     global placeHolder 

     if checker == 0: 
     t1 = Thread(target=test, args=()) 
     t1.start() 

     while placeHolder <= test:    

     response = session.get('https://www.example.com/') 


     opts = ChromeOptions() 
     opts.add_experimental_option("detach", True) 
     driver = Chrome(chrome_options=opts) 

     driver.get(response.url + '#/checkout/login') 
     print "Checking Out..." 

     placeHolder +=1 






if __name__ == '__main__': 
    test = input('How many tasks you want to start? \n') 
    Main() 
+0

我的意思是每个线程一次。当我有7个线程时,它应该运行7次。此代码一般运行一次。 – Dking1199

+0

嗯让我看看。 –

+0

好的,我正在编辑我的代码 –