If Python is interpreted, what are .pyc files?

前端 未结 11 771
夕颜
夕颜 2020-11-22 08:39

I\'ve been given to understand that Python is an interpreted language...
However, when I look at my Python source code I see .pyc files, w

11条回答
  •  死守一世寂寞
    2020-11-22 09:32

    THIS IS FOR BEGINNERS,

    Python automatically compiles your script to compiled code, so called byte code, before running it.

    Running a script is not considered an import and no .pyc will be created.

    For example, if you have a script file abc.py that imports another module xyz.py, when you run abc.py, xyz.pyc will be created since xyz is imported, but no abc.pyc file will be created since abc.py isn’t being imported.

    If you need to create a .pyc file for a module that is not imported, you can use the py_compile and compileall modules.

    The py_compile module can manually compile any module. One way is to use the py_compile.compile function in that module interactively:

    >>> import py_compile
    >>> py_compile.compile('abc.py')
    

    This will write the .pyc to the same location as abc.py (you can override that with the optional parameter cfile).

    You can also automatically compile all files in a directory or directories using the compileall module.

    python -m compileall
    

    If the directory name (the current directory in this example) is omitted, the module compiles everything found on sys.path

提交回复
热议问题