RSS category feeds

RSS site feeds

More

Determine top level script name and directory in Python PDF Print E-mail

This script provides the name and directory of the top level Python script.

Why is this useful?

Sometimes you need information stored in the main script's directory (configuration data, graphics, parameters, etc.)

Why this approach?

The simpler ways of doing this all fail in one or the other situation:
  • Variable "__file__" contains the source name but it is not available when being invoked by execfile or when compiled.
  • Variable "sys.argv[0]" does not work when we are being invoked by execfile.
  • Variable "sys.executable" only works in the compiled case. It does provide directory information and the executable's name, but not the name of the Python source that was used to create it.

ScriptInfo tries to always provide the correct information. It has been tested with Python 2.7.9 / Win7 and py2exe, cx_freeze, PyInstaller, IDLE, IPython (sh) / (Qt), python interpreter.

Sample usage:
 
import scriptinfo as si
 
script_name = si.scriptinfo["name"]      # will contain <toplevel>.py / <toplevel>.exe
script_dir  = si.scriptinfo["dir"]       # will contain directory where <toplevel>.py / <toplevel>.exe sits
script_src  = si.scriptinfo["source"]    # will contain <toplevel>.py
"source" and "name" are identical when running interpreted.
"source" contains the Python name of the script that was compiled yielding the executable - but only in cases py2exe and cx_freeze. "source" has no meaningful information in PyInstaller compilations.
 
def scriptinfo():
    '''
    Returns a dictionary with information about the running top level Python
    script:
    ---------------------------------------------------------------------------
    dir:    directory containing script or compiled executable
    name:   name of script or executable
    source: name of source code file
    ---------------------------------------------------------------------------
    "name" and "source" are identical if running non-compiled code.
    When running code compiled by py2exe or cx_freeze, "source" contains
    the name of the originating Python script.
    If compiled by PyInstaller, "source" contains no meaningful information.
    '''
    import os, sys, inspect
    #---------------------------------------------------------------------------
    # scan through the call stack for caller information
    #---------------------------------------------------------------------------
    for teil in inspect.stack():
        # end of module list?
        if teil[1].startswith("<"):
            break
        # are we being invoked by an "execfile"?
        if teil[3].endswith("execfile"):
            break
        # running under IDLE?
        if teil[3].startswith("runcode"):
            break
        # running cx_freeze compiled?
        if type(teil[4]) is list and teil[4][0].startswith('exec(code'):
            break                
        trc = teil[1]
    
    # check if we have been compiled
    if getattr(sys, 'frozen', False):
        scriptdir, scriptname = os.path.split(sys.executable)
        return {"dir": scriptdir,
                "name": scriptname,
                "source": trc}
 
    # from here on, we are in the interpreted case
    scriptdir, trc = os.path.split(trc)
    # if trc did not contain directory information we take
    # the current working directory
    if not scriptdir:
        scriptdir = os.getcwd()
 
    scr_dict ={"name": trc,
               "source": trc,
               "dir": scriptdir}
    return scr_dict
Last Updated ( Monday, 19 January 2015 )
 
< Prev   Next >

Feedback

Advertisement

Comments

  • I have run your code on my own machine, but I just got the last paragraph of the... More...
  • Hello Gabriel, It seem that the linked site moved to github.com/.../weboutlook (... More...
  • There is no script to download, could you provide the right link More...
  • Interesting but doesn't really help me. I do not see what the 'xxxxx' in the Ses... More...
  • You can see more python editor comparison: sparkledge.com/.../ (http://sparkledg... More...

Login Form






Lost Password?

My prefered Python IDE

My prefered Python editor is Pyscripter from MMExperts. It is not only an editor. Pyscripter is a full Python IDE including (remote) debugging, a class browser, and all other nice helpers which a full featured IDE needs.

Do you have a script for me ?

Do you have an interesting Python script which does some really cool thing on Windows ? Please post them to this site. It`s very simple - simply copy&paste it to this form. No login is requiered.

Hint: For syntax highlighting and correct Python intendation place your code between html tags <pre> and </pre>.

My prefered web framework

My prefered web framework for developing web applications is Django. Django calls itself The web framework for perfectionists with deadlines. It is a really fast, scalable and (thanks Python) the sexiest web framework of the world.