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.
bar.py
would have to behave like the Python interpreter itself and runfoo.py
(orfoo.pyc
, as you asked for that) as if it was the main script. This is surprisingly hard. My 90% solution to do that looks like so:This mimics the default behavior of the Python interpreter relatively closely. It sets system globals
__name__
,__file__
,sys.argv
, inserts the script location intosys.path
, clears the global namespace etc.You would copy that code to
bar.py
or import it from somewhere and use it like so:Then, given this:
and
foo.py
looking like this:... running
foo.py
viabar.py
gives you that:While I'd guess that
run_script_as_main
is lacking in some interesting details, it's pretty close to the way Python would runfoo.py
.You probably have something along the lines of:
Instead, write your code in a function
main()
infoo
and then do:Then, in bar, you can import foo and call
foo.main()
.Additionaly, if you need to change the working directory, you can use the
os.chdir(path)
method, e.g.os.chdir('path/of/bar')
.You can use
execfile()
if the file is.py
and uncompyle2 if the file is.pyc
.Let's say you have your file structure like:
foo.py
bar.py
And in
test/
, if you do:Both, outputs the same:
Please also see this answer.
This solution is what ended up working well for me:
Have you tried this?
bar.py
for me it runs whatever is in foo.py (before and inside main)
After, maybe what you do in bar.py might be more tricky that my basic test.
The good thing with load_source is that it imports the .pyc if it already exists or initiates a "compile" of the .py and then imports the .pyc.
The
foo.py
need not be on the same folder as the main folder. UseTo add the path that
foo
resides to Python path. Now you canAnd make myfunc do whatever u want