2009-12-24 126 views
2

我有一個程序在函數尚未定義時運行。當我將代碼放入函數中時,它不會執行它包含的代碼。有誰知道爲什麼?有些代碼是:函數沒有執行python

def new_directory(): 

if not os.path.exists(current_sandbox): 
    os.mkdir(current_sandbox) 

感謝

+3

那麼,你是怎麼稱呼這個功能的? – 2009-12-24 12:17:24

+1

你有權創建該目錄嗎? – 2009-12-24 12:20:59

+2

嘗試在函數的第一行添加'print'here''。看看控制是否在那裏。可能會發現'不是os.path.exists(current_sandbox)'每次都會給出False。 – 2009-12-24 12:21:17

回答

4

問題1是您定義了一個函數(「def」是「define」的縮寫),但是您不會調用它。

def new_directory(): # define the function 
if not os.path.exists(current_sandbox): 
    os.mkdir(current_sandbox) 

new_directory() # call the function 

問題2(還沒有打你還)是您使用的是全球(current_sandbox)時,你應該使用一個參數 - 在後一種情況下你的函數通常有用的,甚至有用贖回來自另一個模塊。問題3是不規則的縮進 - 使用1的縮進將導致任何必須閱讀你的代碼的人(包括你自己)瘋狂。堅持4並使用空格,而不是標籤。

def new_directory(dir_path): 
    if not os.path.exists(dir_path): 
     os.mkdir(dir_path) 

new_directory(current_sandbox) 
# much later 
new_directory(some_other_path) 
4

您的代碼實際上是一個new_directory函數的定義。除非您致電new_directory(),否則不會執行。 所以,當你想從您的文章執行代碼,只需添加一個函數調用是這樣的:

def new_directory(): 

if not os.path.exists(current_sandbox): 
    os.mkdir(current_sandbox) 

new_directory() 

不知道如果這是你希望得到的行爲。

+0

但通常要好得多把它放在一個'if __name__ =='__main __「:'block中,這樣當模塊僅僅被另一個模塊導入時它將不會被執行。 – 2009-12-24 12:31:23

+0

@Peter Hansen:確實,OP需要通過爬行,走路,跑步等階段,但現在他的石頭一動不動,需要啓動。他的腳本也可能被用作模塊的想法很可能不會發生在他身上。 – 2009-12-24 12:43:40

1
def new_directory(): 
    if not os.path.exists(current_sandbox): 
    os.mkdir(current_sandbox) 

new_directory()