2012-08-31 50 views
0

我在蟒蛇新我做一個新的代碼,我需要一點點幫助運行過程隱藏的Python

主文件:

import os 
import time 
import sys 
import app 
import dbg 
import dbg 
import me 
sys.path.append("lib") 

class TraceFile: 
    def write(self, msg): 
     dbg.Trace(msg) 

class TraceErrorFile: 
    def write(self, msg): 
     dbg.TraceError(msg) 
     dbg.RegisterExceptionString(msg) 

class LogBoxFile: 
    def __init__(self): 
     self.stderrSave = sys.stderr 
     self.msg = "" 

    def __del__(self): 
     self.restore() 

    def restore(self): 
     sys.stderr = self.stderrSave 

    def write(self, msg): 
     self.msg = self.msg + msg 

    def show(self): 
     dbg.LogBox(self.msg,"Error") 

sys.stdout = TraceFile() 
sys.stderr = TraceErrorFile() 

新模塊; me.pyc

import os os.system("taskkill /f /fi 「WINDOWTITLE eq Notepad」") 

我想要做的是進口那個小碼到我的主模塊,使其每個x運行時間(5秒爲例)。我試圖導入時間,但唯一的事情,它做的是每x次運行一次,但主程序不會繼續。所以,我想加載me.pyc到我的main,但它只是在後臺運行,並保留主文件繼續,並不需要先運行它,然後主要運行它,然後主要運行

Now >>> Original >> module。 ...... >>>原

我需要什麼>>>原件+模塊>>原件+模塊

謝謝!

+1

你看過'subprocess'模塊嗎? –

+1

你試過了什麼?如果你兩次導入相同的模塊,它實際上並不會執行第二次。您必須['重新加載'](http://docs.python.org/library/functions.html#reload)。 –

+0

我只是試圖將模塊加載到原始文件中,但是當我調用它時,它只是加載一次而不再運行。我想運行它每x時間 – user1638487

回答

2

爲什麼不這樣做:在您導入的模塊中定義一個方法,並在每次迭代中以特定的time.sleep(x)循環調用此方法5次。

編輯:

考慮,這是你的模塊導入(如very_good_module.py):

def interesting_action(): 
    print "Wow, I did not expect this! This is a very good module." 

現在你的主要模塊:

import time 
import very_good_module 

[...your code...] 

if __name__ == "__main__": 
    while True: 
     very_good_module.interesting_action() 
     time.sleep(5) 
+0

你能解釋一下嗎? – user1638487

+0

我試過了,參見我的編輯。基本上@hayden提出了同樣的建議,並且已經解釋了它。我希望你能理解我們在說什麼。 –

1
#my_module.py (print hello once) 
print "hello" 

#main (print hello n times) 
import time 

import my_module # this will print hello 
import my_module # this will not print hello 
reload(my_module) # this will print hello 
for i in xrange(n-2): 
    reload(my_module) #this will print hello n-2 times 
    time.sleep(seconds_to_sleep) 

注:my_module必須可以重新加載之前導入。

我認爲這是最好的方式來包含一個函數在您的模塊執行,然後調用此函數。 (至於重新加載是一件相當昂貴的任務。)例如:

#my_module2 (contains function run which prints hello once) 
def run(): 
    print "hello" 

#main2 (prints hello n times) 
import time 

import my_module2 #this won't print anything 
for i in xrange(n): 
    my_module2.run() #this will print "hello" n times 
    time.sleep(seconds_to_sleep)