在 Jython 中运行 Python 比特种子追踪器时,我们遇到了一个问题。该追踪器使用 PyCrypto 库,我们已经为其编译了平台并将其添加到 Python 路径中。但是,当我们尝试运行代码时,我们收到了以下错误:
Exception in thread "MainThread" Traceback (most recent call last):
File "./python_dep/BitTorrent-5.2.2/bittorrent-tracker.py", line 21, in <module>
from BitTorrent.track import track
File "./python_dep/BitTorrent-5.2.2/BitTorrent/track.py", line 50, in <module>
from BitTorrent.UI import Size
File "./python_dep/BitTorrent-5.2.2/BitTorrent/UI.py", line 37, in <module>
from BitTorrent.MultiTorrent import UnknownInfohash, TorrentAlreadyInQueue, TorrentAlreadyRunning, TorrentNotRunning
File "./python_dep/BitTorrent-5.2.2/BitTorrent/MultiTorrent.py", line 25, in <module>
from BitTorrent.Torrent import Feedback, Torrent
File "./python_dep/BitTorrent-5.2.2/BitTorrent/Torrent.py", line 32, in <module>
from BitTorrent.ConnectionManager import ConnectionManager
File "./python_dep/BitTorrent-5.2.2/BitTorrent/ConnectionManager.py", line 22, in <module>
from BitTorrent.Connector import Connector
File "./python_dep/BitTorrent-5.2.2/BitTorrent/Connector.py", line 27, in <module>
from Crypto.Cipher import ARC4
ImportError: cannot import name ARC4
Java Result: 1
我们确信该库位于 Python 路径中,因为命令 import Crypto.Cipher 可以正常工作,但 from Crypto.Cipher import ARC4 却不行。
2. 解决方案
为了解决这个问题,我们需要在 Jython 中使用 Java 包装器来调用 PyCrypto C 扩展。可以使用以下方法来解决:
-
首先,我们需要确保 PyCrypto 库已经编译并安装在 Jython 中。可以从 PyCrypto 网站下载并安装该库。
-
其次,我们需要创建一个 Java 包装器来调用 PyCrypto C 扩展。我们可以使用 Jython 的 Java API 来实现这一点。
-
最后,我们需要将 Java 包装器添加到 Jython 的路径中,以便 Jython 能够找到它。
以下是 Java 代码的示例,它演示了如何使用 Java 包装器来调用 PyCrypto C 扩展:
package jythTest;
import org.python.util.PythonInterpreter;
public class Main {
public static void main(String[] args) {
PythonInterpreter pythonInterpreter = new PythonInterpreter();
pythonInterpreter.exec("import sys");
pythonInterpreter.exec("sys.path.append("./python_dep/BitTorrent-5.2.2/")");
pythonInterpreter.exec("sys.path.append("./python_dep/Twisted-10.0.0/")");
pythonInterpreter.exec("sys.path.append("./python_dep/Zope-3.4.0/build/lib.linux-i686-2.6")");
pythonInterpreter.exec("sys.path.append("./python_dep")");
pythonInterpreter.exec("sys.path.append("./python_dep/pycrypto-2.0.1/build/lib.linux-i686-2.6")");
//添加 Java 包装器到路径中
pythonInterpreter.exec("sys.path.append("PATH_TO_JAVA_WRAPPER")");
//pythonInterpreter.exec("print sys.path");
pythonInterpreter.execfile("./python_dep/BitTorrent-5.2.2/bittorrent-tracker.py");
}
}
在上面的代码中,我们首先创建了一个 PythonInterpreter 对象,然后将 PyCrypto 库和 Java 包装器添加到 Python 路径中。最后,我们执行了 bittorrent-tracker.py 文件。
通过使用 Java 包装器,我们现在可以在 Jython 中成功导入 PyCrypto 库。