[Python] Making Python run a few lines before my script

Discussão em 'Python' iniciado por Stack, Fevereiro 19, 2025.

  1. Stack

    Stack Membro Participativo

    I need to run a script foo.py, but I need to also insert some debugging lines to run before the code in foo.py. Currently I just put those lines in foo.py and I'm careful not to commit that to Git, but I don't like this solution.

    What I want is a separate file bar.py that I don't commit to Git. Then I want to run:

    python /somewhere/bar.py /somewhere_else/foo.py


    What I want this to do is first run some lines of code in bar.py, and then run foo.py as __main__. It should be in the same process that the bar.py lines ran in, otherwise the debugging lines won't help.

    Is there a way to make bar.py do this?

    Someone suggested this:

    import imp
    import sys

    # Debugging code here

    fp, pathname, description = imp.find_module(sys.argv[1])
    imp.load_module('__main__', fp, pathname, description)


    The problem with that is that because it uses import machinery, I need to be on the same folder as foo.py to run that. I don't want that. I want to simply put in the full path to foo.py.

    Also: The solution needs to work with .pyc files as well.

    Continue reading...

Compartilhe esta Página