Python3之模块

  在计算机程序的开发过程中,随着程序代码越写越多,在一个文件里代码就会越来越长,越来越不容易维护。

  为了编写可维护的代码,我们把很多函数分组,分别放到不同的文件里,这样,每个文件包含的代码就相对较少,很多编程语言都采用这种组织代码的方式。在Python中,一个.py文件就称之为一个模块(Module)。

  写一个hello的模块hello.py

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

__author__='Liuym'

#导入模块sys
import sys

def test():
    args=sys.argv
    print('命令行所有参数列表',args)
    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()

  导入sys模块后,我们就有了变量sys指向该模块,利用sys这个变量,就可以使用sys模块的所有功能

  sys模块有一个argv变量,用list存储了命令行所有参数。argv至少有一个元素,因为第一个参数永远是该.py文件的名称,例如:

  运行python3 hello.py获得的sys.argv就是['hello.py'] 

  运行python3 hello.py Liuym获得的sys,argv就是['hello.py','Liuym']

  运行结果

[root@prd-zabbix python]# python3 hello.py 
命令行所有参数列表 ['hello.py']
Hello World
[root@prd-zabbix python]# python3 hello.py Liuym
命令行所有参数列表 ['hello.py', 'Liuym']
Hello,Liuym
[root@prd-zabbix python]# python3 hello.py Liuym 123
命令行所有参数列表 ['hello.py', 'Liuym', '123']
Too many arguments

  当我们在命令行运行hello模块文件时,Python解释器把一个特殊变量__name__置为__main__,而如果在其他地方导入该hello模块时,if判断将失败,因此,这种if测试可以让一个模块通过命令行运行时执行一些额外的代码,最常见的就是运行测试。

  

  如果启动python交互环境

>>> import hello

  导入时没有打印Hello World,因为没有执行test()函数调用hello.test()时,才能打印出Hello,World

>>> hello.test()
命令行所有参数列表 ['']
Hello World

  

原文地址:https://www.cnblogs.com/minseo/p/11088233.html