zoukankan      html  css  js  c++  java
  • 初识Python-文件类型(入坑篇)

    一、源代码【.py】
     
    ##Python源代码文件通常以.py为后缀,下面我们通过编写一个简单的Python执行文件,利用print来打印输出的信息hello World。
    [root@master python]# vim hello.py
    #!/usr/bin/python 
    
    print 'hello world'
    语法:python【file.py】

    ##执行一个Python文件,通过命令Python file-name执行文件

    [root@master python]# python hello.py

    hello world

    二、字节代码【.pyc】

    ##通常我们写好的源代码文件.py是可以看到里面的代码内容,如果不想让别人看到里面的源码,可以通过import插入py_compile模块来对源码文件进行编译后,内容变为二进制字符无法查看源码内容,经过编译后会生成一个.pyc的Python文件。

    py_compile.compile('源码文件')

    [root@master python]# vim 2.py

    #!/usr/bin/python 
    
    import py_compile 
    py_compile.compile('hello.py')

    执行文件后,可以看到在源码的基础上,编译出一个新的.pyc文件,源代码文件不存在的情况下,编译过后的代码文件依旧可以执行显示正常的输出信息!!

    [root@master python]# python 2.py

    [root@master python]# ls

    2.py hello.py hello.pyc

    [root@master python]# python hello.pyc

    hello world

    经过编译后的文件内容为二进制字节码,而且类型也发生变化为bety文件

    [root@master python]# vim hello.pyc

    ^Có
    y^N^F^c^@^@^@^@^@^@^@^@^A^@^@^@@^@^@^@s ^@^@^@d^@^@GHd^A^@S(^B^@^@^@s   ^@^@^@hell wordN(^@^@^@^@(^@^@^@^@(^@^@^@^@(^@^@^@^@s^G^@^@^@hell.pyt^H^@^@^@<module>^C^@^@^@s^@^@^@^@

     [root@master python]# file hello.pyc

    hello.pyc: python 2.7 byte-compiled

    三、优化代码【.pyo】

    ##.pyo是优化编译后的文件,同样编译过后的文件内容也是二进制字节码,通过-O表示优化,-m指定调用py_compile 模块执行源码文件。

    语法:python -O -m py_compile【源代码】
    [root@master python]# python -O -m py_compile hello.py
    [root@master python]# ls
    2.py  hello.py  hello.pyc  hello.pyo

    [root@master python]# python hello.pyo

    hello world
  • 相关阅读:
    【Linux】PS命令
    【Linux】多进程与多线程之间的区别
    【杂项】XML Schema和DTD的区别
    推荐一组强大的Collection类
    关于Decorator模式我的理解
    菜鸟白话设计模式系列
    PowerCollections研究: 第1弹竟就发现不少问题
    [白话设计模式] Singleton
    PowerCollection研究:第2枪小谈RemoveALL算法
    yield 关键字
  • 原文地址:https://www.cnblogs.com/douyi/p/12109981.html
Copyright © 2011-2022 走看看