简体   繁体   中英

Getting variables from another python file WITHOUT importing

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)

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

eg 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']

You need to actually grab a reference to the module to be able to reload it:

# First:
import python_vars

# Then:
do_something_with(python_vars.git_branch)

# Later on
reload(python_vars)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM