pythonpyc

How to run a .pyc file when it imports some other .py files?


main.py

import other

def main():
   other.test()

main()

other.py

def test():
   print("Hello")

By using python3 -m py_compile *.py, I can have 2 .pyc files.

However, main.pyc cannot be run if there is no module named other, which is the error I got from the terminal.

The idea is to compile the entire project from .py to .pyc so that people can run them without sharing the source code.

So, how to run this main.pyc which imports other libraries, while not sharing the source code?


Solution

  • Asked a machine learning group. Here is what I found. As long as, main.py and other.py are compiled to main.pyc and other.pyc, I can run it by python3 main.pyc.

    Before this, my python automatically converts other.py to other.cpython-35.pyc. In this case, main.pyc cannot import other since there is no other in the folder (it's called other.cpython-35 now).

    Thus, make sure .pyc file have the same name as .py, and then you can run any of them and python will include .pyc file for you when you execute the command.