Python自定义模块管理

2024-10-01 19:34:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个剧本_搁置.py)它通过指定键从shelve-storage检索数据,例如:

def get_shelve_users(field):
    import shelve
    db = shelve.open('oracle-shelve')
    for key in db:
        if key == field:
             return db[key]
    db.close()

数据检索得很好:

print(get_shelve_users('db_users'))
> {'SYS': 'sysdba'}
print(get_shelve_users('oratab'))
> ['orcl:/u01/app']

另一个脚本应该执行相同的操作(使用指定的键检索数据),该脚本已导入dump\u或shelve,但返回的值为Null:

from before_OOP.dump_ora_shelve import get_shelve_users
print(get_shelve_users('db_users'))
> Null
print(get_shelve_users('oratab'))
> Null

要导入的文件位于它要导入到的文件的上一级。你知道吗

请注意,如果我复制两个文件到同一个位置导入,然后功能正常工作。你知道吗


Tags: 文件数据keyimport脚本fielddbget
2条回答

当运行第二个脚本时,您的工作目录将是该脚本所在的目录。即使从不同的包/目录导入和使用文件,也会保留该工作目录。你知道吗

所以如果你的垃圾桶_搁置.py脚本和搁置位于不同的目录/包中,因此无法打开正确的文件。你知道吗

如果您在dump\u ora中提供“oracle shelve”的完整路径_搁置.py应该有用。你知道吗

更新:

在你的垃圾堆里_搁置.py'文件:

ABS_DIR = os.path.dirname(os.path.abspath(__file__))

这将为您提供“dump\u ora”目录的绝对路径_搁置.py'. 加入数据库名称:

shelve_db = os.path.join(ABS_DIR, 'oracle-shelve')

最后:

db = shelve.open(shelve_db)

这假设您的“oracle shelve”与“dump\u ora”位于同一目录中_搁置.py'

您可以提供shelve.open的完整路径名。请记住,在模块中,__file__是源文件所在的路径。所以你可以用它来构造完整的路径名。你知道吗

通常你会有这样的情况:

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

使用os.path.join连接目录和文件名。注意os.path.dirnameos.path.abspath的用法。你知道吗

所以你可以说:

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
shelve_db = os.path.join(BASE_DIR, 'oracle-shelve')
db = shelve.open('oracle-shelve')

这假设orache-shelve文件与get_shelve_users函数所在的模块(dump_ora_shelve.py)位于同一文件夹中。你知道吗

别忘了__file__。这就是使整个程序运行的原因,也就是说,使程序与当前目录隔离。你知道吗

相关问题 更多 >

    热门问题