等到条件满足

时间:2017-08-02 11:59:40

标签: python multithreading

我是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')

2 个答案:

答案 0 :(得分: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块。

答案 1 :(得分: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()