0

Whenever I tried to run my python script in unix nothing would happen. I'd type something along the lines

 $ python script.py

and all that would be returned is

 $

Now I know it isn't a problem in my code because that runs fine in idle, so I figured I needed to add something else to my code to be able to run it from the command line. In a google tutorial on python I was introduced to boilerplate code which is tacked onto the end of a function as such

def main():
  print ...
  etc etc
if __name__ == '__main__':
  main()

And if I write a function called main and run it just like that it works fine. However when I named my function something else, anything else, it won't work. E.g.

def merge():
  print ..
  etc etc
if __name__ == '__merge__':
  merge()

That function won't produce any output at all on the command line Even if I just went and removed the n from the end of word main, each time it occurs in the main function above, it won't work. How does one make python functions run on the command line? and what the heck is up with python only letting functions called main be run?

Thanks!

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
TheFoxx
  • 1,583
  • 6
  • 21
  • 28
  • 2
    please read [this](http://stackoverflow.com/questions/419163/what-does-if-name-main-do). – sloth Dec 06 '12 at 15:06
  • if python is not installed, he would not see an empty prompt, more likely a bunch of "command not found" – Samuele Mattiuzzo Dec 06 '12 at 15:10
  • Is the question here "why does a Python program that runs in IDLE not run on Unix", or "why does Python only run functions called `main`"? – me_and Dec 06 '12 at 15:10

2 Answers2

2

When you run a python script from the command line, __name__ is always '__main__'.

Try something like:

def merge():
  print ..
  etc etc
if __name__ == '__main__':
  merge()

From the Python interpreter, you have to do something more like:

>>> import script
>>> script.merge()
MrMas
  • 1,143
  • 2
  • 14
  • 28
  • well, it's not always "main", just main if it's the main module. if imported, it has not the name "main" – Samuele Mattiuzzo Dec 06 '12 at 15:08
  • Yeah -- I made an edit to reflect what I meant. – MrMas Dec 06 '12 at 15:10
  • Yup, thats it. You know I thought that might have been it, then I thought to myself, "No that's stupid what kind of tutorial would teach you write a function called main and then reference something else entirely called main within it, like why not call the function something else"... God damn it google. – TheFoxx Dec 06 '12 at 15:11
2
__name__ == "__main__"

should not be changed, if you run code from the same file you have your functions on

if __name__ == "__main__":
    merge()

don't bother about that if only you're importing that module within another file

This link explains you a bith more

Samuele Mattiuzzo
  • 10,760
  • 5
  • 39
  • 63