导入“pyc”进入现有的python脚本 [英] importing "pyc" into existing python script

查看:759
本文介绍了导入“pyc”进入现有的python脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试添加一个目录,我可以在其中抛出一些pyc文件并从我的脚本中调用它们。

I'm trying to add a directory where I can throw some pyc files and call them from my script.

基本上它是一个独立的python脚本,里面有一堆def,
我希望pyc文件的名称是执行的命令。
到目前为止这个工作正常,除了一件事,我的GUI按钮调用defs因为它们是
并且python因为名称空间错误而无法识别它们。

Basically it's an independent python script with a bunch of def's in it, I want the name of the pyc file to be the command executed. so far this works ok except for one thing, my GUI buttons are calling defs as they are and python doesn't recognize them since the name space is wrong.

如何从脚本中导入它,就像导入它一样:

How can I import it in from the script as if it was imported like :


从模块导入为*

from Module import as *

我正在运行此代码以加载它:

I'm running this code to load it in:

def importModule(ModPath):
    fullModName= ModPath.split('\\')[-1]
    commandtorun=fullModName.split('.')[0]

    mod_name,file_ext = os.path.splitext(os.path.split(ModPath)[-1])
    if file_ext.lower() == '.py':
        py_mod = imp.load_source(mod_name, ModPath)
    elif file_ext.lower() == '.pyc':
        py_mod = imp.load_compiled(mod_name, ModPath)

    exec "from %s import *"%(commandtorun)
    exec "%s()" % (commandtorun)

我知道我可以写:module.somefun ction(),但那不是我需要的......
i需要模块独立工作..

i know i can write : module.somefunction() , but that's not what i need... i need the "module" to work independently..

请帮忙,这让我抓狂,python是一种非常棒的语言我不能相信你不能从脚本中获取脚本并让它工作。
请指教。

Please help, this is driving me crazy, python is such an awesome language I cant believe you can't source a script from within a script and have it work. please advise.

推荐答案


  • 您可以在<$ c $中使用(稀有的Python)分号c> exec 打电话给你提供一个 exec

  • 你可能想拿在 import_module(name,package) > importlib

    • You could use a (rare-in-Python) semicolon in your exec call to make one exec out of the two you have
    • You might want to take a look at import_module(name, package) in importlib
    • 这篇关于导入“pyc”进入现有的python脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆