简体   繁体   中英

Cannot import Python function in Jython

I wrote a Python script which is executed via Jython 2.7. I need SQLite, so I decided to use sqlite3 for Jython ( link ) which is under /usr/local/lib/jython/Lib .

ghidra_batch.py

import sys
sys.path.append("/usr/local/lib/jython/Lib")
sys.path.append("/path/to/my/project/directory")
import sqlite3

I created another file where I define some functions for my database:

db.py

import platform
import sys
if platform.python_implementation == 'Jython':
    sys.path.append("/usr/local/lib/jython/Lib")
    sys.path.append("/path/to/my/project/directory")
import sqlite3

def open_db():
   [some code]

def create_schema():
   [some code]

Note: I check Python implementation because this script is run also via CPython. I append the path only when run via Jython to make it find its sqlite3 module, in case of CPython standard sqlite3 module is used.

Now my problem happens when I import open_db() in ghidra_batch.py:

from db import open_db

The result is the following:

ImportError: cannot import name open_db

Thanks for your help.

As a general rule: when working with Python , when something isn't not what you're expecting, simply print it.

Your from db import open_db line which was triggering that exception "told" me that:

  • The db module (package) was found
  • It's not the one that you're expecting to be (your db.py )

That's why I suggested in my comment to print information about it (obviously, before the error is hit):

import db
print(db)
print(dir(db))

The output confirmed it. So, there is another db module which is imported before yours. I tried replicating your environment (installed Jython , but I wasn't able to install jython-sqlite3 ).
After a bit of research, I think it's [BitBucket]: Taro L. Saito/sqlite-jdbc/Source - sqlite-jdbc/src/main/java/org/sqlite/DB.java ( sqlite-jdbc is a jython-sqlite3 dependency).

The reasonable way is to modify your module name to something else (eg: sqlite_db_wrapper.py ), and also update the import statement(s).

As a(n other) general rule, don't give your modules (common) names that might conflict with modules from Python 's library .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM