Python代码不能使用系统变量

2024-04-26 03:58:59 发布

您现在位置: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。你知道问题出在哪里吗?在


Tags: thepathfromimporthomeossystools
3条回答

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

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

相反。 第一个'..'将您带到“tutorial”文件夹中,第二个位于“docs”文件夹中,第三个位于“bin”、“tools”和“docs”所在的主文件夹中。在

你为什么要加一美元?变量的名称是SUMO_HOME,而不是$SUMO_HOME。在

我也有一些问题。如果我在我的终端上回音,它显示了正确的路径,但在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'

我知道这是一个迟来的评论,你可能已经解决它或继续前进,但希望它仍然会帮助其他人!在

谨致问候

伊莎贝尔

相关问题 更多 >

    热门问题