3

I have a program that runs when the functions have not been defined. When I put code into a function, it does not execute the code it contains. Why? Some of the code is:

def new_directory():

    if not os.path.exists(current_sandbox):
        os.mkdir(current_sandbox)
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
chrisg
  • 40,337
  • 38
  • 86
  • 107

3 Answers3

4

Your code is actually a definition of a new_directory function. It won't be executed unless you make a call to new_directory().

So, when you want to execute the code from your post, just add a function call like this:

def new_directory():

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

new_directory()

I am not sure if that's the behavior you expect to get.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Alexei Sholik
  • 7,287
  • 2
  • 31
  • 41
  • But generally much better to put that in an `if __name__ == "__main__":` block so it won't get executed when the module is merely imported by another. – Peter Hansen Dec 24 '09 at 12:31
  • @Peter Hansen: Indeed the OP needs to move through crawl, walk, run stages, but right now he's stone cold motionless and needs kick-starting. The thought that his script might also be used as a module may quite possibly not have occurred to him. – John Machin Dec 24 '09 at 12:43
4

Problem 1 is that you define a function ("def" is an abbreviation of "define"), but you don't call it.

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

new_directory() # call the function

Problem 2 (which hasn't hit you yet) is that you are using a global (current_sandbox) when you should use an argument -- in the latter case your function will be generally useful and even usefully callable from another module. Problem 3 is irregular indentation -- using an indent of 1 will cause anybody who has to read your code (including yourself) to go nuts. Stick to 4 and use spaces, not tabs.

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)
John Machin
  • 81,303
  • 11
  • 141
  • 189
1
def new_directory():  
  if not os.path.exists(current_sandbox):  
     os.mkdir(current_sandbox)

new_directory() 
YOU
  • 120,166
  • 34
  • 186
  • 219