Compiling main script into .pyc

S

Sam

One thing I observe about python byte-code compiling is that the main script does not gets compiled into .pyc. Only imported modules are compiled into .pyc.

May I know how can I compile the main script into .pyc? It is to inconvenience potential copy-cats.
 
B

bob gailer

One thing I observe about python byte-code compiling is that the main script does not gets compiled into .pyc. Only imported modules are compiled into .pyc.

May I know how can I compile the main script into .pyc?
Duh? Just import it!
 
N

Ned Batchelder

One thing I observe about python byte-code compiling is that the main script does not gets compiled into .pyc. Only imported modules are compiled into .pyc.

May I know how can I compile the main script into .pyc? It is to inconvenience potential copy-cats.

The standard library has the compileall module that can be used to
create .pyc files from .py files, but as we've been discussing in
another thread, you may not want .pyc files.
 
D

Dave Angel

MRAB said:
What if you want to just compile it? Importing will run it!

Importing will only run the portion of the code not protected by

if __name__ == "__main__":
 
T

Terry Reedy

What if you want to just compile it? Importing will run it!

Write the main script as

def main(): ...
if __name__ == '__main__': main()

The difference between merely compiling 'def main' and executing it is
trivial.

Or don't bother compiling and write main.py as one line:
from realmain import start; start()
 
S

Steven D'Aprano

Importing will only run the portion of the code not protected by

if __name__ == "__main__":


Nevertheless, there is no need to run *any* of the code just to compile
it.


[steve@ando ~]$ cat sample.py
print("Hello!")

[steve@ando ~]$ ls sample.pyc
ls: sample.pyc: No such file or directory
[steve@ando ~]$ python -m compileall sample.py
Compiling sample.py ...
[steve@ando ~]$ ls sample.p*
sample.py sample.pyc
[steve@ando ~]$ python sample.pyc
Hello!
 
G

Grant Edwards

[steve@ando ~]$ cat sample.py
print("Hello!")

[steve@ando ~]$ ls sample.pyc
ls: sample.pyc: No such file or directory
[steve@ando ~]$ python -m compileall sample.py
Compiling sample.py ...
[steve@ando ~]$ ls sample.p*
sample.py sample.pyc
[steve@ando ~]$ python sample.pyc
Hello!

Cool! Now I can distribute my application as a pre-compiled "binary"
just like I do for <insert language/platform/OS here>.

[That was meant ironically, BTW]
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top