How to use same python cgi file on windows and linux (apache)?

Viewed 1747

Using python as CGI on linux/apache server, The first line (one that defines the interpreter, shebang) should be like this:

#!/usr/bin/env python 

Running same python CGI on windows/apache server, the first line (one that defines the interpreter) should be like this: (assuming that python installed to c:/python27)

#!c:/python27/python.exe

Is there option to set identical line so that no changes will be needed while moving files from linux to windows?

2 Answers

So you have the shebang line #!/usr/bin/env python What you are missing in Windows is literally the env.exe application.

  1. Download the following ZIP files from the GnuWin project https://sourceforge.net/projects/gnuwin32/files/coreutils/5.3.0/:

    • coreutils-5.3.0-bin.zip

    • coreutils-5.3.0-dep.zip

  2. Create \usr\bin folder on the same drive, where Apache HTTP for Windows starts from, for example: c:\usr\bin

  3. Extract into created \usr\bin folder:

    • env.exe from coreutils-5.3.0-bin.zip;

    • libiconv2.dll, libintl3.dll from coreutils-5.3.0-dep.zip

  4. You should have the following files there:

    C:\usr\bin>dir
     Volume in drive C is OSDisk
     Volume Serial Number is DEAD-BEEF
    
     Directory of C:\usr\bin
    
    01/23/2019  10:24 AM    <DIR>          .
    01/23/2019  10:24 AM    <DIR>          ..
    04/20/2005  01:41 PM            24,064 env.exe
    03/16/2004  03:37 PM           898,048 libiconv2.dll
    10/09/2004  11:25 AM           101,888 libintl3.dll
                   3 File(s)      1,024,000 bytes
    

Bingo! Now your Apache will interpret the shebang line correctly.

A bonus step

For those who would like to run Python CGI scripts from Python virtual environment.

  1. If you have Python virtual environment created in c:\py-venv, add the following lines into an Apache httpd.conf for a directory where your Python CGI scripts will be located. The scripts will be executed by Apache using Python virtual environment's binaries and modules.

    # Python virtual environment folder
    Define VENV "c:/py-venv"
    # Python CGI scripts location
    Define PY_CGI "c:/test/cgi"
    
    <Directory "${PY_CGI}">
        AllowOverride None
        Order allow,deny
        Allow from all
        Options ExecCGI FollowSymLinks
        Options -Indexes
        Require all granted
        SetEnv VIRTUAL_ENV ${VENV}
        SetEnv PATH "${VENV}/Scripts;${PATH}"
    </Directory>
    
Related