how to “source” file into python script

后端 未结 7 1024
孤街浪徒
孤街浪徒 2020-12-10 11:39

I have a text file /etc/default/foo which contains one line:

FOO=\"/path/to/foo\"

In my python script, I need to reference the

7条回答
  •  余生分开走
    2020-12-10 12:02

    There are a couple ways to do this sort of thing.

    • You can indeed import the file as a module, as long as the data it contains corresponds to python's syntax. But either the file in question is a .py in the same directory as your script, either you're to use imp (or importlib, depending on your version) like here.

    • Another solution (that has my preference) can be to use a data format that any python library can parse (JSON comes to my mind as an example).

    /etc/default/foo :

    {"FOO":"path/to/foo"}
    

    And in your python code :

    import json
    
    with open('/etc/default/foo') as file:
        data = json.load(file)
        FOO = data["FOO"]
        ## ...
        file.close()
    

    This way, you don't risk to execute some uncertain code...

    You have the choice, depending on what you prefer. If your data file is auto-generated by some script, it might be easier to keep a simple syntax like FOO="path/to/foo" and use imp.

    Hope that it helps !

提交回复
热议问题