Python 在执行文件时更改sys.path

Python 在执行文件时更改sys.path,python,path,python-import,Python,Path,Python Import,我正在为我的GitHub存储库设置Travis CI,在创建测试时,我意识到我遇到了一个问题 我的文件结构如下: parent-dir: src: prog.py generator.py test: test.py Travis被设置为运行test.py文件,然后执行以下命令: variables = {'help': '-h'} execfile(sys.path[0] + "/../src/prog.py", variabl

我正在为我的GitHub存储库设置Travis CI,在创建测试时,我意识到我遇到了一个问题

我的文件结构如下:

parent-dir:
    src:
        prog.py
        generator.py
    test:
        test.py
Travis被设置为运行test.py文件,然后执行以下命令:

variables = {'help': '-h'}
execfile(sys.path[0] + "/../src/prog.py", variables)
这工作正常。但是问题是,
prog.py
generator.py
导入为:

from generator import generate, languages
运行测试时,我得到错误:
ImportError:没有名为generator的模块

我四处窥探,发现执行第二个文件时,
sys.path[0]
没有更新

我的问题是,有没有一种方法可以在执行另一个文件时获取要更新的路径,或者有更好的方法可以简单地获取正在操作的模块的位置

我的代码如下:

test.py

import os
import unittest2

import tests # Self reference for working directory.
relative_dir = os.path.dirname(tests.__file__)

class Test(unittest2.TestCase):
    def test_program(self):
        msg('Attempting to generate example utility.') # just prints the message, nothing interesting
        variables = {'help': '-h'} # command line variables
        execfile(relative_dir + "/../src/prog.py", variables)
import os

import prog # This file.
relative_dir = os.path.dirname(dash_h.__file__)
prog.py

import os
import unittest2

import tests # Self reference for working directory.
relative_dir = os.path.dirname(tests.__file__)

class Test(unittest2.TestCase):
    def test_program(self):
        msg('Attempting to generate example utility.') # just prints the message, nothing interesting
        variables = {'help': '-h'} # command line variables
        execfile(relative_dir + "/../src/prog.py", variables)
import os

import prog # This file.
relative_dir = os.path.dirname(dash_h.__file__)
我不会费心去显示
generator.py
,因为这已经足够完整了。不管生成器如何,即使只是简单地从自身导入
prog
,也会抛出完全相同的错误

ImportError: No module named prog
我正在从父目录目录在终端中执行以下命令:

python -B test/test.py

如果存在后者,我实际上希望将其合并到所有其他文件中。

我的建议是将输入文件的路径作为命令行参数传递。

您在这里的目的是什么?你到底想完成什么?@Code学徒我正在使用unittest2测试另一个文件夹中的文件。但我不想简单地运行一个函数,我想用参数执行它,就像它是从命令行执行的一样。如果你从同一个目录执行同一个命令,它能工作吗?@finrayment请提供一个最小的完整示例。这不应该是您的全部代码。事实上,在这种情况下,您应该制作一个非常做作的示例来展示您试图实现的目标。@finnrayment请再次阅读我之前的评论,并查看帮助部分以获取有关创建MCVE.Hmmm…的提示。。。。这就是问题所在。我不能依靠
tests.py
来解析它的参数,因为每个参数都必须在程序执行时解析。@finrayment tests.py不应接受任何要解析的参数。正在测试的应用程序是否已经需要其他参数?这是正确的<代码>测试。py
只是直接运行。该应用程序本身是一个命令行实用程序,它循环使用所有接收到的参数。我想通过提供要解析的数据来测试这个功能。这就是为什么我不能解析它的路径,因为通过设计,它会试图理解路径,并最终将其存储在一个我不希望的变量中。