我有一个程序,它在函数还没有定义的时候运行。当我将代码放入一个函数中时,它不会执行它包含的代码。有人知道为什么吗?其中的一些代码是:
def new_directory():
if not os.path.exists(current_sandbox):
os.mkdir(current_sandbox) 谢谢
发布于 2009-12-24 20:56:45
问题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)发布于 2009-12-24 20:21:20
您的代码实际上是一个new_directory函数的定义。除非您调用new_directory(),否则它不会被执行。因此,当您想要从post执行代码时,只需添加一个函数调用,如下所示:
def new_directory():
if not os.path.exists(current_sandbox):
os.mkdir(current_sandbox)
new_directory()不确定这是否是您期望得到的行为。
发布于 2009-12-24 20:21:32
def new_directory():
if not os.path.exists(current_sandbox):
os.mkdir(current_sandbox)
new_directory() https://stackoverflow.com/questions/1958134
复制相似问题