Python - 在子文件夹中的另一个脚本中执行函数

标签 python variables parent-child working-directory

我有一个主脚本,它在主目录的子文件夹中执行多个子脚本。

文件夹层次结构如下所示:

MyFolder\MasterScript.py
MyFolder\ChildOneScript\ChildOne.py
MyFolder\ChildTwoScript\ChildTwo.py
MyFolder\ChildThreeScript\ChildThree.py

从 MasterScript 中,我需要调用 ChildOne“myChildFunction”中的函数并向其传递一些变量。问题是,我不能简单地做

import ChildOneScript.ChildOne as ChildOne
ChildOne.myChildFunction

因为还有其他脚本依赖ChildOne的相对路径。因此,如果我从 MasterScript 将 ChildOne 导入到 MyFolder 目录并在那里调用 myChildFunction,我会收到回溯错误,指出找不到其他文件。这是由于另一个顽固的程序员所犯的错误,他拒绝更改他的相对路径调用,因为这是大量的手动工作。

那么,有没有办法从 MasterScript 中调用 myChildFunction 向其传递一些变量?

我知道我可以使用 subprocess.call 及其 cwd 参数来更改工作目录,但我无法弄清楚是否可以调用特定的 myChildFunction 并使用 subprocess 向其传递变量。

编辑:是否可以使用 execfile 传递变量?

最佳答案

您始终可以使用 os 模块破解它。它并不漂亮,但它可能是您无需重写所有其他人的代码即可做到的最好的方法。如果您将经常使用其他脚本中的函数,我会为它们编写一个包装器,以便更轻松地调用它们:

import sys
import os

def call_legacy_func(func, *args, **opts):
    prev = os.path.abspath(os.getcwd()) # Save the real cwd
    try:
        # Get the child's physical location.
        func_path = sys.modules[func.__module__].__file__
    except:
        # Die; we got passed a built-in function (no __file__)
        # Or you could just call it, I guess: return func(*args, **opts)
        return None

    # Change to the expected directory and run the function.
    os.chdir(func_path)
    result = func(*args, **opts)

    # Fix the cwd, and return.
    os.chdir(prev)
    return result

import ChildOneScript.ChildOne as ChildOne
call_legacy_func(ChildOne.myChildFunction, 0, 1, kwarg=False)

关于Python - 在子文件夹中的另一个脚本中执行函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15366886/

相关文章:

python - 如何使用具有不同项目 ID 的现有 Compute Engine 中的 Google Cloud Datastore?

python - 了解 hyperopt TPE 算法

python - 总结 Pandas DataFrame 中的列值

javascript - Jquery - 一个 .click 事件中的两个变量

delphi - 为什么Assigned 对于未初始化的变量返回 true?

java - 具有相同类的父子的 JPA 映射

python - Sphinx 不识别子文件夹

java - 从 GridView 项目中获取值

带有无尽子项的 MySQL 嵌套 SELECT 查询

php - "Notice: Undefined variable"、 "Notice: Undefined index"、 "Warning: Undefined array key"和 "Notice: Undefined offset"使用 PHP