Python代码不能使用系统变量

时间:2014-08-21 20:46:52

标签: python

我的代码的以下部分出现问题:

import os, sys
import optparse
import subprocess
import random

# we need to import python modules from the $SUMO_HOME/tools directory
try:
    sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..', '..', '..', "tools")) # tutorial in tests
    sys.path.append(os.path.join(os.environ.get("$SUMO_HOME", os.path.join(os.path.dirname(__file__), "..", "..", "..")), "tools")) # tutorial in docs
    from sumolib import checkBinary
except ImportError:
    sys.exit("please declare environment variable 'SUMO_HOME' as the root directory of your sumo installation (it should contain folders 'bin', 'tools' and 'docs')")

import traci

我将SUMO_HOME声明为系统变量,但是当我运行此脚本时,我得到了ImportError。你知道问题是什么吗?

3 个答案:

答案 0 :(得分:1)

你为什么要加$?变量的名称为SUMO_HOME,而不是$SUMO_HOME

答案 1 :(得分:1)

我也遇到了一些问题。如果我在我的终端中回显它显示正确的路径,但在python文件中它以某种方式找不到它。对我来说,通过将try-except块修改为:

来修复它
# we need to import python modules from the $SUMO_HOME/tools directory
try:
    sys.path.append(<Path to tools>)
    from sumolib import checkBinary
except ImportError:
    sys.exit(
        "please declare environment variable 'SUMO_HOME' as the root directory of your sumo installation (it should contain folders 'bin', 'tools' and 'docs')")

因此,在我的示例中,我使用了此块并将<Path to tools>替换为'/Users/Isabelle/sumo-0.28.0/tools'

我知道这是一个迟到的评论,你可能已经解决了它或继续前进,但希望它仍然可以帮助别人!

亲切的问候,

伊莎贝尔

答案 2 :(得分:0)

此解决方案可能仅适用于MAC OS。不确定其他操作系统。 我发现了什么问题,我不知道为什么但是python代码中'..'的数量有误。你需要删除一个。需要3而不是4。 它应该是:

sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..', '..', "tools")) # tutorial in tests

代替。 第一个'..'带您进入'tutorial'文件夹,第二个进入'docs'文件夹,第三个进入'bin','tools'和'docs'所在的主文件夹。