1

したがって、次のようなディレクトリツリーがあります。

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) で実行すると空のディクショナリが得られます。

4

4 に答える 4

0

プラグインに識別子がない場合に警告を出力するステートメントにelse:ブランチを配置しますif

また、行末は気にしないかもしれませんのでfirstline.strip()、チェック時に呼び出すと問題が解決する場合があります

最後に、根本的に、使用する代わりにパスに参加fileすることができますpluginFolderNameos.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)
于 2012-04-04T03:24:30.943 に答える
0

私の問題を理解しました!の

os.path.isfile(file)

Linux がプラグイン ファイルへの絶対パスを要求したため、テストは機能しませんでした。したがって、ファイルのすべてのインスタンスを

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

すべてを修正するようです。

于 2012-04-04T18:21:16.850 に答える
0

ソース コードに Windows CRLF 行末がありますか? の代わりにa を追加して、print repr(firstline)末尾が でないことを確認してください。\r\n\n

于 2012-04-04T02:58:46.773 に答える