python 相对路径导入模块报错,由不同模块导入时如何访问Python 2.7中的相对路径...

The Goal:

Access / Write to the same temp files when using a common utility function called from various python modules.

Background:

I am using the python Unittest module to run sets of custom tests that interface with instrumentation via pySerial. Because I am using the unittest module, I am unable to pass required variables, such as which serial port to use, into the unittest's test case. To get around this I am wanting to create a module that stores and returns pickled data. I have run into the issue that when I call the function get_foo() from test_case_1(), it tries to load the pickled data from the relative path based on test_case_1(), not the actual module that contains get_foo().

It is worth noting that I have contemplated using global variables, but there is a handful of data that I want to retain from run to run. Meaning that all python modules will be closed and I want to re-load the data that was stored on the previous execution.

I in SO question: Python - how to refer to relative paths of resources when working with code repository, I thought I found the solution in the first answer. To my dismay, this is not working for me in Python 2.7 (Debian)

Is there an reliable way to return the path to a specific file when called from different modules?

解决方案

Probably you know this, but here the basics first:

## file one: main.py, main program in your working directory

# this code must run directly, not inside IDLE to get right directory name

import os, mytest

curdir=os.path.dirname(__file__)

print '-'*10,'program','-'*10

print 'Program in',curdir

print 'Module is in', mytest.curdir

print 'Config contents in module directory:\n',mytest.config()

input('Push Enter')

The module

## file two: mytest.py, module somewhere in PATH or PYTHONPATH

import os

curdir= os.path.dirname(__file__)

print "Test module directory is "+curdir

## function, not call to function

config=open(os.path.join(curdir,'mycfg.cfg')).read

""" Example output:

Test module directory is D:\Python Projects

---------- program ----------

Program in D:\test

Module is in D:\Python Projects

Config contents in module directory:

[SECTIONTITLE]

SETTING=12

Push Enter

""""

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值