相当于允许'from module import *'的label或goto

时间:2013-06-27 17:23:55

标签: python python-3.x python-3.3

我开发了一套简单的基于多语言控制台的计算器,我的问题是,在第一次执行时,当用户选择他的语言时,他会得到软件标题的两倍。

------------------------------------------------------
Trooper Math Suite - ver. 0.1.5.1
------------------------------------------------------
Choose your default language:
------------------------------------------------------
1. English
2. Português Brasileiro
3. Español
------------------------------------------------------
You: 1
------------------------------------------------------
Trooper Math Suite - ver. 0.1.5.1
------------------------------------------------------
Select the calculator:
------------------------------------------------------
1. Biquadratic Equations Calculator
2. Pythagorean Theorem Calculator
------------------------------------------------------
You: 

启动器的代码是:

# tms.py - launcher

ver = "0.1.5.1"
sep = "-" * 54

print(sep)
print("Trooper Math Suite - ver. {0}".format(ver))
print(sep)

try:
    from config import *

    if default_lang == "1":
        print("""Select the calculator:\n{0}
1. Biquadratic Equations Calculator
2. Pythagorean Theorem Calculator\n{0}""".format(sep))
        go = input("You: ")
        print(sep)
        if go == "1": import bc
        elif go =="2": import pc

    if default_lang == "2":
        print("""Selecione a calculadora:\n{0}
1. Calculadora de Equações Biquadradas
2. Calculadora do Teorema de Pitágoras\n{0}""".format(sep))
        go = input("You: ")
        print(sep)
        if go == "1": import bc
        elif go =="2": import pc

    if default_lang == "3":
        print("""Seleccione la calculadora:\n{0}
1. Calculadora de Ecuaciones Bicuadráticas
2. Calculadora de Teorema de Pitágoras\n{0}""".format(sep))
        go = input("You: ")
        print(sep)
        if go == "1": import bc
        elif go =="2": import pc

except:
    print("""Choose your default language:\n{0}
1. English
2. Português Brasileiro
3. Español\n{0}""".format(sep))
    language=input("You: ")

    while language != "1" and language != "2" and language != "3":
        print(sep)
        print("You must choose between 1, 2 or 3.")
        print(sep)
        language=input("You: ")

    file = open("config.py", "w")
    file.write('default_lang = "{0}"\n'.format(language))
    file.close()
    import tms

我用Google搜索,人们建议使用def lang()之类的函数,但我不能这样做,因为:

SyntaxError: import * only allowed at module level

1 个答案:

答案 0 :(得分:3)

最好的解决方案是不要使用import *。相反,请保留模块命名空间,并在需要的地方使用import configconfig.some_object

可以说,更好的是为您的配置文件使用另一种格式,例如JSON。这将使配置文件的使用更容易,并避免恶意配置文件的可能性。