What's% {__ python34} in a python script?

I see one python script starting with

#!%{__python34}

from __future__ import unicode_literals
# Whether we're Python 2

      

I'm guessing __python34 is used to get the path to python2 or python 3.4, but it doesn't work as the output says the file doesn't exist ...

Thank.

+3


source to share


1 answer


I believe this is a technique known as "templating" ( %{var}

used, for example, in the template engine used by RPM , as we can see in this example , especially see the file .spec

). And many of these templates exist, Jinja2 , Mako , etc. etc. (a more comprehensive list can be found here )

Now let's use Jinja2 to create a simple example, the first thing we create is a template (let's put it in a folder templates

to follow the convention), call it python_script_tmpl:

#!{{ python }}

def main():
    print("It works")

      

Now create init (empty script) to create an environment for use with Jinja2.

You should now have a structure like:

myapp/
  __init__.py
  templates/
    python_script_tmpl

      

Start a shell in the directory my_app

and run the following line ( doc to install jinja2 ):

from jinja2 import Environment, PackageLoader
env = Environment(loader=PackageLoader("__init__", "templates")) #use the blank __init__ script to init the environment, and the templates folder to load templates
tmpl = env.get_template("python_script_tmpl") #load the template 
tmpl.stream(python="/usr/bin/env python3").dump("python_script.py") #create from the template a script called python_script.py

      



And now in the root of my_app you should have a script python_script.py

and it should look like this:

#!/usr/bin/env python3

def main():
    print("It works")

      

With the final folder structure:

myapp/
  __init__.py
  python_script.py
  templates/
    python_script_tmpl

      

Assuming the shebang and env are configured correctly , you can run the script without issue. (although not a very useful script)

Now, what's the point of templating?

If you need to repeat batches many times (like a shebang) and need to change it, then you have to change it for every file where it appears, if you use a template you just need to change the variable once and inject it. This is the direct advantage of templates.

PS: As @CharlesDuffy mentions, this script is probably being pulled from a package RPM

, so except for tutorial purposes or repackaging, I suggest you use the rpm command line tool to run the entire package.

+2


source







All Articles