导入命令的输出而不是文件-python

导入命令的输出而不是文件-python,python,import,Python,Import,我有一个非常简单的脚本,我想测试一下 主脚本(caller.py): 函数/模块脚本(test2.py): 当我运行caller.py时,它就工作了。因为test2.py脚本存在于我调用caller.py的同一目录中 如果需要通过变量使test2.py中定义的函数可用于caller.py脚本,会发生什么情况?有时test2.py函数脚本的内容并不总是在文件中。有时,它在一个变量中 基本上,我在寻找一种方法来访问变量中的函数,就像导入访问文件中的函数一样 我希望能够做到以下几点: from com

我有一个非常简单的脚本,我想测试一下

主脚本(caller.py):

函数/模块脚本(test2.py):

当我运行caller.py时,它就工作了。因为test2.py脚本存在于我调用caller.py的同一目录中

如果需要通过变量使test2.py中定义的函数可用于caller.py脚本,会发生什么情况?有时test2.py函数脚本的内容并不总是在文件中。有时,它在一个变量中

基本上,我在寻找一种方法来访问变量中的函数,就像导入访问文件中的函数一样

我希望能够做到以下几点:

from commands import *

def run_command(cmd):
    status, text = getstatusoutput(cmd)
    print text

run_command('python /tmp/test2.py')
test2.printMe()
请告知。

尝试以下方法:

from sys import path as sys_path
from os import path

def import_module(path_to_py_file):
    dir_name, module_name = path.split(path.splitext(path_to_py_file)[0])
    sys_path.append(dir_name)
    return __import__(module_name)
现在您可以执行以下操作:

test2 = import_module(r'/tmp/test2.py')
test2.printMe()

看看,我已经为此挣扎了一段时间了。你能提供一些真实的例子吗?到底是什么?“test2.py的内容有时在变量中”是什么意思?这是否意味着您有一个包含python代码的巨大字符串?这是否意味着您有一个类似于
“python/tmp/test2.py”
的字符串?在这两种情况下,为什么?这个变量来自哪里?我可以做一些类似于:test2=import_module('cat/tmp/test2.py')的事情吗
from sys import path as sys_path
from os import path

def import_module(path_to_py_file):
    dir_name, module_name = path.split(path.splitext(path_to_py_file)[0])
    sys_path.append(dir_name)
    return __import__(module_name)
test2 = import_module(r'/tmp/test2.py')
test2.printMe()