python 的 main method

之前看 python 文章好像都沒提到怎麼寫 main method, 似乎這件事情很自然, 不過我卻不知道.
看了 6.1.1. Executing modules as scripts 裡面有寫
"the code in the module will be executed, just as if you imported it, but with the __name__ set to "__main__". That means that by adding this code at the end of your module:"
if __name__ == "__main__":
    import sys
    fib(int(sys.argv[1]))
試著作一次

  1. C:\Python33\say.py
    def say(words):
            print(words)
    
    if __name__ == '__main__':
            import sys
            say(sys.argv[1])
            print(__name__,sys.argv[0])
    
    
  2. Output
    C:\Python33>python.exe say.py hello
    hello
    __main__ say.py

這樣就可以了, 很簡單..

沒有留言:

張貼留言

別名演算法 Alias Method

 題目 每個伺服器支援不同的 TPM (transaction per minute) 當 request 來的時候, 系統需要馬上根據 TPM 的能力隨機找到一個適合的 server. 雖然稱為 "隨機", 但還是需要有 TPM 作為權重. 解法 別名演算法...