Altering sys.argv on startup in Python 2

Random832 random832 at fastmail.com
Sun Jun 12 13:51:17 EDT 2016


On Sun, Jun 12, 2016, at 08:56, Adam Bartoš wrote:
> Hello,
> 
> I'm trying to employ code like
> https://code.activestate.com/recipes/572200/
> at Python 2 startup. The problem is that sys.argv isn't polulated yet
> when
> sitecustomize is executed. Is there any way around? I was thinking about
> something like temporarily chaning sys.modules['sys'] or sys.__dict__ to
> something that runs my code on PySys_SetArgv, but that doesn't work since
> PySys_SetArgv doesn't invoke any hooks like __setitem__ on sys.__dict__.
> So
> is there any way how to automatically run my code after sys.argv was set
> but before executing the main script (in Python 2)?

>From what I can tell, if you create a path hook in sitecustomize.py,
argv will have been set before the hook is called for the script.

So, for example:

import sys

edit_done = False
def argv_setter_hook(path):
    global edit_done
    if edit_done:
        return
    try:
        argv = sys.argv
    except AttributeError:
        pass
    else:
        argv[:] = get_unicode_argv()
        edit_done = True
    raise ImportError # let the real import machinery do its work

sys.path_hooks[:0] = [argv_setter_hook]



More information about the Python-list mailing list