Python从另一个目录调用文件

时间:2015-04-08 16:30:54

标签: python laravel-5

我一直试图找到答案,但我所看到的只是从另一个目录中读取文件或从另一个目录运行文件。我确定我想要做的事情并不难,但我是新手,并且不知道如何描述它的所谓。

我有一个位于/ src目录下的python脚本run.py。我从/ src目录运行该脚本。 run.py调用两个文件(configuration.py和server.py)。这两个文件位于名为lib(src / lib)的文件夹中。所有文件夹都有一个空的__init__.py文件。

当我从lib中取出这些文件并将它们放在src中时,我可以在脚本看起来像下面那样运行脚本。

import os
import inspect
import sys


import configuration
import server


# Initialize Parameters
f_path = os.path.abspath(inspect.getfile(inspect.currentframe()))
absolute_path = os.path.dirname(f_path)


if __name__ == "__main__":
    from optparse import OptionParser, OptionGroup

    parser = OptionParser()

    parser.usage = "usage: %prog [options] "

    parser.description = "Primary application entry point."

    parser.add_option("-v", "--verbose", dest="verbose", action="store_true",
                  default=False, help="Run verbose.")

    group = OptionGroup(parser, "Node operations")

    group.add_option("--do-queue-job", dest="do_queue_job", action="store_true",
                 help="Run the next job in the quasar-server queue.")

    parser.add_option_group(group)

    (options, args) = parser.parse_args()

    # Clear argv to prevent issues with web.py automatically using arguments to
    # bind ip addresses.
    sys.argv = []

    configuration = configuration.Configuration("/home/mscarpa/PhpstormProjects/quasar-node/quasar-node/quasar-node/src/config.yml")


    if (options.do_queue_job):
        # Get server instance
        server_connection = server.QuasarConnection(configuration)
        #return server_connection

        # Get next job from server
        next_job = server_connection.get_next_job()
        #return next_job

我知道如果将两个文件移动到/ src / lib,我必须更改代码的两部分如下:

    configuration = configuration.Configuration("/home/mscarpa/PhpstormProjects/quasar-node/quasar-node/quasar-node/src/config.yml")

    server_connection = server.QuasarConnection(configuration)

我在想,我只需要将put.lib放在他们面前,但每次尝试时都会说lib没有定义。

    configuration = lib.configuration.Configuration("/home/mscarpa/PhpstormProjects/quasar-node/quasar-node/quasar-node/src/config.yml")

    server_connection = lib.server.QuasarConnection(configuration)

这可能是一个noob问题,但有人知道如果这些文件位于src / lib目录而不是src目录中,那么如何定位这些文件

2 个答案:

答案 0 :(得分:2)

您只需要更改import语句以反映模块的新位置:

import lib.configuration as configuration
import lib.server as server

你的其余部分并不需要改变。

答案 1 :(得分:0)

我明白了。我认为你的答案可能在某些情况下有效,但我认为我的问题是新的问题是找出要搜索的内容。

这是一个sys.arg的东西所以我必须在导入文件之前将该路径包含在该lib文件夹中。

sys.path.insert(0, '/home/mscarpa/PhpstormProjects/quasar-node/quasar-node/quasar-node/src/lib')


import configuration
import server
相关问题