我对 python 和 ruby 都很陌生。
我创建了一个 python 脚本,它像这样导入它的依赖项:
import sys
sys.path.append("/usr/share/anki")
from anki import Collection
from anki.importing import TextImporter
如何在 RubyPython 中实现相同的功能?除此之外,我尝试过:
RubyPython.start
sys = RubyPython.import("sys")
sys.path.append("/usr/share/anki")
Collection = RubyPython.import("anki.Collection")
TextImporter = RubyPython.import("anki.importing.TextImporter")
RubyPython.stop
这给了我一个错误:`import': AttributeError: 'module' object has no attribute 'argv' (RubyPython::PythonError)
for the line for anki.Collection import.
我也尝试过这样的事情:
RubyPython.start
sys = RubyPython.import("sys")
sys.path.append("/usr/share/anki/anki")
Collection = RubyPython.import("collection")
TextImporter = RubyPython.import("anki.importing.TextImporter")
RubyPython.stop
这给了我一个错误:`import': ImportError: 对于集合导入行,没有名为 anki.lang (RubyPython::PythonError) 的模块
。从the source code for anki可以看到这是在 collection.py 文件中导入的第一个内容。
最佳答案
Python 解释器是嵌入的,因此一些特定于进程的位是有意义的,例如sys.argv
不可用。
这是一个没有 ruby 的快速测试:
In [1]: import sys
In [2]: del sys.argv
In [3]: sys.path.append("anki")
In [6]: import anki.Collection
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-6-ff326ec5c6ff> in <module>()
----> 1 import anki.Collection
/dima/anki/anki/__init__.py in <module>()
32
33 version="2.0.16" # build scripts grep this line, so preserve formatting
---> 34 from anki.storage import Collection
35 __all__ = ["Collection"]
/dima/anki/anki/storage.py in <module>()
4
5 import os, copy, re
----> 6 from anki.lang import _
7 from anki.utils import intTime, json
8 from anki.db import DB
/dima/anki/anki/lang.py in <module>()
103
104 if not currentTranslation:
--> 105 setLang("en_US", local=False)
/dima/anki/anki/lang.py in setLang(lang, local)
82 def setLang(lang, local=True):
83 trans = gettext.translation(
---> 84 'anki', langDir(), languages=[lang], fallback=True)
85 if local:
86 threadLocal.currentLang = lang
/dima/anki/anki/lang.py in langDir()
75 os.path.abspath(__file__)), "locale")
76 if not os.path.isdir(dir):
---> 77 dir = os.path.join(os.path.dirname(sys.argv[0]), "locale")
78 if not os.path.isdir(dir):
79 dir = "/usr/share/anki/locale"
AttributeError: 'module' object has no attribute 'argv'
理想情况下,您的代码不应依赖于 sys.argv
,例如,考虑一下,如果您的模块被另一个项目使用,您就无法假设 sys.argv< 中最终会发生什么
.
如果您想要代码/资源目录,请使用
os.path.dirname(__file__)
代替(*)如果您确实需要
sys.argv
,请在导入模块之前将假数组注入(inject)sys
。
(*)请记住,Python 代码也可以作为 zip 提供,在这种情况下,您甚至没有传统意义上的目录。
关于python - RubyPython 导入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19677009/