2015-09-23 28 views
0

我有一個試圖執行的完全相同的功能兩條平行線以下Python代碼「ex.py」:機器人框架使用python多線程,涉及嵌套函數調用

import thread 

class PrtArg(object): 

    def print_name1(tname,*args): 
     cnt = 0 
     print "Inside print_name1" 
     while cnt < 10: 
      cnt += 1 
      print "%s : %s\n" % (tname, cnt) 

    def print_name(tname,*args): 
     cnt = 0 
     print "Inside print_name" 
     while cnt < 10: 
      cnt += 1 
      print "%s : %s\n" % (tname, cnt) 

    def m_prt(self,*args): 
     thread.start_new_thread(print_name, (args[0],)) 
     thread.start_new_thread(print_name1, (args[1],)) 

而且我有測試套件 「example.robot」 有以下幾點:

*** Settings *** 
Documentation MultiThread Program 
Library ex.PrtArg 

*** Test Cases *** 
Test title 
    [Documentation] MultiThread 
    [Tags] DEBUG 
    m_prt a b 

*** Keywords 

當我執行,我得到了以下錯誤:

============================================================================== 
Ex :: MultiThread Program 
============================================================================== 
Test title :: MultiThread            | FAIL | 
NameError: global name 'print_name' is not defined 
------------------------------------------------------------------------------ 
Ex :: MultiThread Program           | FAIL | 
1 critical test, 0 passed, 1 failed 
1 test total, 0 passed, 1 failed 
============================================================================== 

現在,我遇到了this,它說「線程通常只能從主線程與框架進行通信」。那不是上面的代碼做什麼?我甚至沒有回報價值。只是打印到控制檯。正如預期的那樣,當我修改我的「example.robot」到下,它工作正常:

*** Settings *** 
Documentation MultiThread Program 
Library example4.PrtArg 

*** Test Cases *** 
Test title 
    [Documentation] MultiThread 
    [Tags] DEBUG 
    print_name a 
    print_name1 b 

*** Keywords *** 

所以,我的問題是:

  1. 我如何運行靜態關鍵字的測試用例哪些調用python庫中的其他功能?這可能嗎?
  2. 這種方式是多線程支持的機器人框架嗎?
  3. 我在這裏錯過了什麼嗎?

回答

1

你應該嘗試聲明你的方法是靜態的,因爲它們是在一個類的實例中,並且start_new_thread沒有這樣做。

所以,你的代碼將看起來像

import thread 

class PrtArg(object): 
    @staticmethod 
    def print_name1(tname,*args): 
     cnt = 0 
     print "Inside print_name1" 
     while cnt < 10: 
      cnt += 1 
      print "%s : %s\n" % (tname, cnt) 

    @staticmethod 
    def print_name(tname,*args): 
     cnt = 0 
     print "Inside print_name" 
     while cnt < 10: 
      cnt += 1 
      print "%s : %s\n" % (tname, cnt) 

    def m_prt(self,*args): 
     thread.start_new_thread(PrtArg.print_name, (args[0],)) 
     thread.start_new_thread(PrtArg.print_name1, (args[1],)) 
+0

由於一噸。有效!所以,不是線程或嵌套函數調用的問題。讓我困惑的是,作爲一個獨立的腳本,同樣的工作正常。 –

+0

歡迎您。你可以設置你的帖子爲解決;) – DontPanic57