Python 模塊引入,腳本執行
阿新 • • 發佈:2018-11-10
copyright stderr [1] mes info stdout lag sub enc
引入模塊
創建一個fibo.py
def fib(n): # write Fibonacci series up to n
a, b = 0, 1
while b < n:
print b
a, b = b, a+b
引入這個文件,就可以使用了
>>> import fibo
>>> fibo.fib(100)
1
1
2
3
5
8
13
21
34
55
89
或者
>>> from fibo import fib >>> fib(100) 1 1 2 3 5 8 13 21 34 55 89
或者
>>> from fibo import *
>>> fib(10)
1
1
2
3
5
8
作為腳本執行
fibo.py
def fib(n):
a,b = 0,1
while b < n:
print b
a,b = b,a+b
if __name__ == "__main__":
import sys
fib(int(sys.argv[1]))
# python fibo.py 50
1
1
2
3
5
8
13
21
34
dir() 函數
>>> import fibo >>> dir(fibo) ['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'fib'] >>> import sys >>> dir(sys) ['__displayhook__', '__doc__', '__egginsert', '__excepthook__', '__name__', '__package__', '__plen', '__stderr__', '__stdin__', '__stdout__', '_clear_type_cache', '_current_frames', '_getframe', '_mercurial', '_multiarch', 'api_version', 'argv', 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dont_write_bytecode', 'exc_clear', 'exc_info', 'exc_type', 'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info', 'float_repr_style', 'getcheckinterval', 'getdefaultencoding', 'getdlopenflags', 'getfilesystemencoding', 'getprofile', 'getrecursionlimit', 'getrefcount', 'getsizeof', 'gettrace', 'hexversion', 'last_traceback', 'last_type', 'last_value', 'long_info', 'maxint', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'ps1', 'ps2', 'py3kwarning', 'pydebug', 'setcheckinterval', 'setdlopenflags', 'setprofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout', 'subversion', 'version', 'version_info', 'warnoptions']
Python 模塊引入,腳本執行