[Tutor] .pyc files and executables?

Lance E Sloan lsloan@umich.edu
Thu, 16 Aug 2001 09:08:21 -0400

alan.gauld@bt.com wrote:
> > > What I want to know is this:  If I run myprogram.py, which starts up
> > > the interpreter, will Python see myprogram.pyc there and use it
> > > instead of reparsing the code in myprogram.py?
> > > 
> > If I'm not mistaken, that's precisely what will happen. 
> I don't think so, AFAIK it will always run the script you specify but 
> if that script imports a module it will use the compiled module.
> I guess the definitive answer can only be found in the source again!
> I don't know if you can run pyc files directly, that might work...

I found that I can't run .pyc files directly from the UNIX commandline.
They are not in an executable format.

I think I did find the answer, though.  Using Python's "-v" option
proved very helpful.  First, to set up the problem, I ran Python
interactively, without any options, and imported myprogram.py in
order to make myprogram.pyc.  Then I exited the interpreter.

Next, I ran myprogram, using this command:

  % python -v myprogram.py

Among the output, I didn't see any mention of myprogram.pyc.  I also
tried this by adding "-v" to the end of the Python shebang (#!) line at
the beginning of the program and running it directly.  The results were
the same.

Finally, I ran Python interactively, with "-v" and imported my program.
As with the previous experiment, there was lots of output, but I've
edited most of it out here:

  % python -v
  Python 2.0 (#1, Jan  8 2001, 10:18:58) 
  [GCC egcs-2.91.66 19990314 (egcs-1.1.2 release)] on sunos5
  Type "copyright", "credits" or "license" for more information.
  >>> import myprogram
  # myprogram.pyc matches myprogram.py
  import myprogram # precompiled from myprogram.pyc
  hello from my program

So, Alan, I believe you're correct.  Python will use .pyc files for
modules that are imported, but not for the main program.

So, I might look into mod-python, if I can talk my webmasters into
giving me access to their configured Apache code.  I think I'll need
that in order for the module to compile properly.

Lance E Sloan
Web Services, Univ. of Michigan: Full-service Web and database design,
development, and hosting.  Specializing in Python & Perl CGIs.
http://websvcs.itd.umich.edu/ - "Putting U on the Web"