Is it possible to 'compile' a script?

Andrew MacIntyre andymac at bullseye.apana.org.au
Sat Oct 5 23:05:12 EDT 2002


On Fri, 4 Oct 2002, solosnake wrote:

> This interests me in particular :
> > Note that Python already compiles scripts internally
> > to a bytecode before executing them, and does most
> > things that are reasonably practical to interpret
> > the bytecode as quickly as possible.
>
> So *in theory* at least what I am asking after is not impossible, and at
> some level is already inside Python. My suggestion to those responsible for
> maintaining Python is to differentiate between calling a script which is
> then parsed and compiled into bytecode and executed, and calling a function
> which will parse and create the bytecode, but return a handle to that (now
> faster) bytecode and allow it to be executed through this handle.

The basic approach for this in a scripting environment is as follows:

1) make your code a module, which has at the end something like this:

  if __name__ == '__main__':
      doit()

where doit() is the main routine of your code.

2) compile the module by importing it from the interactive interpreter
(gives you the .pyc file).

3) create a caller script like so:

  #!/usr/local/bin/python
  import <your_module>
  <your_module>.doit()

With a large and/or complex chunk of code, this saves having to recompile
everything except the caller script on each invocation.

It is also prudent to ensure that all of Python's standard library has
been compiled.  I believe there have been examples of Linux distros not
compiling the library when installing Python (using said distro's standard
Python package), which tends to slow things down unnecessarily.

--
Andrew I MacIntyre                     "These thoughts are mine alone..."
E-mail: andymac at bullseye.apana.org.au  | Snail: PO Box 370
        andymac at pcug.org.au            |        Belconnen  ACT  2616
Web:    http://www.andymac.org/        |        Australia






More information about the Python-list mailing list