开发者

How to import a variable from different file types

I am trying to obtain a variable from a different file type and import it into a Python script. The file is version.mk, it has a variable called VARIABLE_ID. The import module does not work as normally, is there any way to call variables from other file types?

Thanks for any help

import os

from version import VERSION_ID

def versionid:

    print VERSION_ID

This is the code that does not work.

The version ID is 0.0.2 format. When I run the below code it says there is a syntax error in the number.

I have read that d开发者_JAVA技巧istutils has a version numbering convention. I am not sure how this could be used, has anyone heard or know how this works?

Is there a way of having cooments in this file, when comments are in the file it interferes with the file. Could the read() just read the version_id and not the comments, thanks

VERSION_ID=map(int,re.match("VERSION_ID\s*=\s*(\S+)",open("version.mk").read()).group(1).split("."))


If you are sure about version.mk is valid python file, and does not have any harm codes, you can execute it.

>>> exec(open("version.mk"))
>>> print VERSION_ID
1

UPDATE: because OP Added VERSION_ID is not a valid python number

version.mk

#version no is here
VERSION_ID=0.0.2

#some more info here
....

-

>>> import re
>>> VERSION_ID=map(int,re.search("VERSION_ID\s*=\s*(\S+)",open("version.mk").read()).group(1).split("."))
>>> VERSION_ID
[0, 0, 2]


If your file isn't Python code, you can't import it as if it were.

You need to open the file manually and parse for the setting. Especially if the line containing the number is something like

VERSION_ID = 0.0.2

Since this can never be valid Python (there's no literal that looks like that).

This might be a case where a regular expression makes sense, something like r'VERSION_ID\s*=\s*([0-9.]+) could work.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜