user3605780
user3605780

Reputation: 7072

Can I pre-compile a python script?

I have a python script. Lets say http://domain.com/hello.py, which only prints "Hello, World!".

Is it possible to precompile this Python file?

I get around 300 requests per second and the overhead of compiling is way to high. In Java the server can handle this easily but for calculations Python works much easier.

Upvotes: 8

Views: 22087

Answers (3)

Stuart Cook
Stuart Cook

Reputation: 1

via the python interface where your python source file is abc.py:

  1. import py_compile
  2. py_compile.compile('abc.py')

Upvotes: 0

Joran Beasley
Joran Beasley

Reputation: 113988

the problem is not that you need to "precompile" python, the problem is that you are trying to execute python scripts using normal cgi script stuff...

the real answer is to use a better web backend than simple cgi to run your python

I would suggest the following in order of appearance

  1. nginx + gnunicorn
  2. apache2 + mod-wsgi
  3. something else
  4. anything else
  ...
n-1. fcgi
  n. cgi

I know this isnt really an answer and is entirely opinion based

Upvotes: 11

Will
Will

Reputation: 24699

Python code is compiled automatically the first time it is run, by the CPython (standard Python) interpreter. You can pre-compile it if you want to optimize the first request, but that usually isn't necessary. Aside from that, you'd need to convert your Python code into a Python C / cython Module. There are some tools to help you convert Python code into a Python Module if that's the route you want to go.

There's also a Python module called SciPy that's commonly used for Scientific Computing and Data Science applications, which provides a tool called Weave which allows you to inline C/C++ code into your Python code allowing certain performance-critical portions of the code to run using compiled C/C++ code.

Upvotes: 1

Related Questions