Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting variables from another python file WITHOUT importing

Tags:

python

I'm trying to write a cleanup script for my jenkins server. Without going into too many details, I want to get a variable from a file in each docroot and match it against something, in a for loop.

So, as seemingly every single google result told me to, I tried adding the docroot to the sys.path.append(docroot), then used imp to find the module, imported it using

imp.find_module('python_vars')
from python_vars import git_branch

and used the variable.

The problem here is that it works for the first one, but then it's already loaded, and doesn't change in the loop. So I'm trying to remove the docroot from the sys.path at the end of each iteration, and then reload the module on the next one using

reload('python_vars')
from python_vars import git_branch

This gives me a 'reload() argument must be module'. And

reload(python_vars)
from python_vars import git_branch

gives me 'NameError: name 'python_vars' is not defined'

Tbh, this seems like a horrible way to do it, is there not an easier way to get a variable from a file?

In php I would simply do something like include(docroot) in the loop and it would overwrite the variable in memory and it's done.

Here's the full loop, which I am fully aware is rubbish, but I'm just trying stuff out for now.

if os.path.exists(docroot):
        sys.path.append(docroot)
        # If docroot exists need to check if it is meant to
        import imp
        try:
                imp.find_module('python_vars')
                from python_vars import git_branch
                remove_project = check_for_git_branch(docroot, git_branch)
        except ImportError:
                remove_project = True
                print 'importerror'
        try:
                imp.find_module('python_vars')
                reload(python_vars)
                from python_vars import git_branch
        except ImportError:
                print 'nope'

        sys.path.remove(docroot)
like image 567
Michael Mallett Avatar asked Feb 10 '26 16:02

Michael Mallett


1 Answers

You can evaluate the contents of a Python file using execfile.

e.g. Say this is the contents vars.py:

git_branch = 'feature/awesome'

Then script.py could do:

execfile('./vars.py')
print git_branch

Of course this has just been evaluated in the global scope, which could be a bit dangerous, so a safer option would be to pass in a dict to store the globals evaluated in vars.py:

vars = {}
execfile('./vars.py',vars)
print vars['git_branch']
like image 198
steevee Avatar answered Feb 13 '26 15:02

steevee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!