How to run python functions in unix?

Possible Duplicate:
What does <if __name__==“__main__”:> do?

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. Eg

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!


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()

__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

链接地址: http://www.djcxy.com/p/9322.html

上一篇: 在python中定义main()

下一篇: 如何在unix中运行python函数?