2012-04-04 64 views
1

所以我有一个目录树如下:在Windows编程进口的作品,但不能在Linux上

pluginlist.py 
plugins/ 
    __init__.py 
    plugin1.py 
    plugin2.py 
    ... 

而且想连接一个类似命名的字典从每个plugin1的,plugin2等

我这样做的方式是(从pluginlist.py)如下:

import os 

pluginFolderName = "plugins" 
pluginFlag = "##&plugin&##" 

commands = {} 

os.chdir(os.path.abspath(pluginFolderName)) 

for file in os.listdir(os.getcwd()): 
    if os.path.isfile(file) and os.path.splitext(file)[1] == ".py": 
     fileo = open(file, 'r') 
     firstline = fileo.readline() 
     if firstline == "##&plugin&##\n": 
      plugin_mod = __import__("plugins.%s" % os.path.splitext(file)[0]) 
      import_command = "plugin_commands = plugin_mod.%s" %  os.path.splitext(file)[0] 
      exec import_command 
      commands = dict(commands.items() + plugin_commands.commands.items()) 
print commands 

(打印命令也用于测试目的)

在Windows上运行该命令会提供正确的命令字典,但在Linux(Ubuntu Server)上运行它会提供一个空字典。

+1

你不能使用'plugin_commands = getattr(plugin_mod,os.path.splitext(file)[0])'而不是'exec'吗? – Blender 2012-04-04 02:53:57

回答

0

想通了我的问题!

os.path.isfile(file) 

测试不起作用,因为Linux想要一个插件文件的绝对路径。所以用

os.path.join(os.getcwd(), file) 

替换文件的所有实例似乎修复一切。

2

尝试:

for file in os.listdir(os.getcwd()): 
    basename, ext = os.path.splitext(file) 
    if os.path.isfile(file) and ext == ".py": 
     with open(file, 'r') as fileo: 
      firstline = fileo.readline() 
      if firstline.startswith("##&plugin&##"): 
       plugin_mod = __import__("plugins.%s" % basename, fromlist = [True]) 
       plugin_commands = getattr(plugin_mod, basename) 
       commands.update(plugin_commands.commands) 

当你调用__import__('A.B'),返回包A。 当您拨打__import__('A.B', fromlist = [True])时,返回模块B。在我看来,你想要B。因此,在Windows和Linux上,您都需要将fromlist设置为非空列表。

+0

这不是它失败的原因,但它仍然有助于更通俗地做事,所以谢谢 – glittershark 2012-04-04 18:22:09

0

您的源代码是否有Windows CRLF行结尾?尝试添加print repr(firstline)以检查它是否以\r\n而不是\n结尾。

0

我会把一个else:分支上if声明,如果一个插件缺少标识

而且它打印警告,你可能不关心行结尾,因此调用firstline.strip()时检查可能会解决您问题

最后,迂腐,你可以加入filepluginFolderName路径,而不是使用os.chdir()

未测试:

pluginFolderName = "plugins" 
pluginFlag = "##&plugin&##" 

pluginFolderName = os.path.abspath(pluginFolderName) 

commands = {} 
for file in os.listdir(pluginFolderName): 
    # Construct path to file (instead of relying on the cwd) 
    file = os.path.join(pluginFolderName, file) 

    if os.path.isfile(file) and os.path.splitext(file)[1] == ".py": 
     fileo = open(file, 'r') 
     firstline = fileo.readline() 

     if firstline.strip() == pluginFlag: 
      # Strip firstline to ignore trailing whitespace 

      plugin_mod = __import__("plugins.%s" % os.path.splitext(file)[0]) 
      plugin_cmds = getattr(plugin_mod, os.path.splitext(file)[0]) 
      commands.update(plugin_cmds) 
     else: 
      print "Warning: %s is missing identifier %r, first line was %r" % (
       file, PLUGIN_IDENTIFIER, firstline) 
相关问题