我有一个程序在函数尚未定义时运行。当我将代码放入函数中时,它不会执行它包含的代码。有谁知道为什么?有些代码是:函数没有执行python
def new_directory():
if not os.path.exists(current_sandbox):
os.mkdir(current_sandbox)
感谢
我有一个程序在函数尚未定义时运行。当我将代码放入函数中时,它不会执行它包含的代码。有谁知道为什么?有些代码是:函数没有执行python
def new_directory():
if not os.path.exists(current_sandbox):
os.mkdir(current_sandbox)
感谢
问题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)
您的代码实际上是一个new_directory
函数的定义。除非您致电new_directory()
,否则不会执行。 所以,当你想从您的文章执行代码,只需添加一个函数调用是这样的:
def new_directory():
if not os.path.exists(current_sandbox):
os.mkdir(current_sandbox)
new_directory()
不知道如果这是你希望得到的行为。
但通常要好得多把它放在一个'if __name__ =='__main __“:'block中,这样当模块仅仅被另一个模块导入时它将不会被执行。 – 2009-12-24 12:31:23
@Peter Hansen:确实,OP需要通过爬行,走路,跑步等阶段,但现在他的石头一动不动,需要启动。他的脚本也可能被用作模块的想法很可能不会发生在他身上。 – 2009-12-24 12:43:40
def new_directory():
if not os.path.exists(current_sandbox):
os.mkdir(current_sandbox)
new_directory()
那么,你是怎么称呼这个功能的? – 2009-12-24 12:17:24
你有权创建该目录吗? – 2009-12-24 12:20:59
尝试在函数的第一行添加'print'here''。看看控制是否在那里。可能会发现'不是os.path.exists(current_sandbox)'每次都会给出False。 – 2009-12-24 12:21:17