Skip to content Skip to sidebar Skip to footer

Why Is My Python Function Not Being Executed?

I have written a script that is pretty temperamental with indentation so I decided to make functions. I'm pretty new to python and now that I've created these functions nothing wor

Solution 1:

It sounds like you need to do this:

def main():
    wiki_scrape()
    all_csv()
    wiki_set = scraped_set('locations.csv')
    country_set = all_set('all.csv')
    print wiki_set

main() # this calls your main function

Even better:

def main():
    wiki_scrape()
    all_csv()
    wiki_set = scraped_set('locations.csv')
    country_set = all_set('all.csv')
    print wiki_set

if __name__ == '__main__':
    main() # this calls your main function

Then run it from the command line like this:

python file_name.py

The built-in variable __name__ is the current contextual namespace. If you run a script from the command line, it will be equivalent to '__main__'. If you run/import the .py file as a module from somewhere else, including from inside the interpreter, the namespace (inside of the context of the module) will be the .py file name, or the package name if it is part of a package. For example:

## my_file.py ##print('__name__ is {0}'.format(__name__))
if __name__ = '__main__':
    print("Hello World!")

If you do this from command line:

python my_file.py

You will get:

__name__ is __main__
Hello World!

If you import it from the interpreter, however, you can see that __name__ is not __main__:

>>>from my_file import *>>>__name__ is my_file

Solution 2:

Python doesn't call any functions on starting unless explicitly asked to (including main).

Instead Python names the files being run, with the main file being run called __main__.

If you want to simply call the main function you can use Rick's answer.

However in Python best practice it is better to do the following:

if __name__ == '__main__':
    wiki_scrape()
    all_csv()
    wiki_set = scraped_set('locations.csv')
    country_set = all_set('all.csv')
    print wiki_set

This ensures that if you are running this python file as the main file (the file you click on, or run from the cmd) then these functions will be run.

If this is instead used as an imported module, you can still use the functions in the script importing the module, but they will not be called automatically and thus won't interfere with the calling script.

Post a Comment for "Why Is My Python Function Not Being Executed?"