#!/usr/bin/env python3
# -*- coding: utf-8 -*-
' a test module '
__author__ = 'Michael Liao'
import sys
def test():
args = sys.argv
if len(args)==1:
print('Hello, world!')
elif len(args)==2:
print('Hello, %s!' % args[1])
else:
print('Too many arguments!')
if __name__=='__main__':
test()
__author__ Author information
Import the sys module
sys
The module has a argv
variable, all the parameters of the command line are stored in list. argv
At least one element, because the first parameter is always the name of the .py file
What you python3 hello.py
get from running sys.argv
is ['hello.py']
;
What you python3 hello.py Michael
get by running sys.argv
is ['hello.py', 'Michael']
.
When we run the module file on the command linehello
, the Python interpreter sets a special variable __name__
to __main__
, and if the hello
module is imported elsewhere , the if
judgment will fail. This method is often used to test!
$ python3 hello.py
Hello, world!
$ python hello.py Michael
Hello, Michael!
$ python3
Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 23 2015, 02:52:03)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import hello
#直接调用方法才会运行test
>>> hello.test()
Hello, world!
Variable definitions:
__xxx__ means special variables, for example __author__
,__name__
_xxx
And __xxx
such functions or variables are non-public (private) and should not be directly quoted, for example _abc
,__abc,这些变量用户可以自己定义。
参考来源:
https://www.liaoxuefeng.com/wiki/1016959663602400/1017455068170048