bash – how to source file into python script

bash – how to source file into python script

Same answer as @jil however, that answer is specific to some historical version of Python.

In modern Python (3.x):

exec(open(filename).read())

replaces execfile(filename) from 2.x

You could use execfile:

execfile(/etc/default/foo)

But please be aware that this will evaluate the contents of the file as is into your program source. It is potential security hazard unless you can fully trust the source.

It also means that the file needs to be valid python syntax (your given example file is).

bash – how to source file into python script

If you know for certain that it only contains VAR=QUOTED STRING style variables, like this:

FOO=some value

Then you can just do this:

>>> with open(foo.sysconfig) as fd:
...   exec(fd.read())

Which gets you:

>>> FOO
some value

(This is effectively the same thing as the execfile() solution
suggested in the other answer.)

This method has substantial security implications; if instead of FOO=some value your file contained:

os.system(rm -rf /)

Then you would be In Trouble.

Alternatively, you can do this:

>>> with open(foo.sysconfig) as fd:
...   settings = {var: shlex.split(value) for var, value in [line.split(=, 1) for line in fd]}

Which gets you a dictionary settings that has:

>>> settings
{FOO: [some value]}

That settings = {...} line is using a dictionary comprehension. You could accomplish the same thing in a few more lines with a for loop and so forth.

And of course if the file contains shell-style variable expansion like ${somevar:-value_if_not_set} then this isnt going to work (unless you write your very own shell style variable parser).

Leave a Reply

Your email address will not be published. Required fields are marked *