zoukankan      html  css  js  c++  java
  • 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
    

      

  • 相关阅读:
    如何创建一个自定义和定制Windows窗体事件“跳转列表吗
    动画应用程序的主窗体
    Splasher v1.32 -启动屏幕实现
    颜色需要
    选项卡对话框类
    捕捉屏幕的各种方法
    列表生成方式
    关于日志监控中,关键字段如果还有.该如何处理
    oracle的一些状态查询
    rpm
  • 原文地址:https://www.cnblogs.com/minseo/p/11088233.html
Copyright © 2011-2022 走看看