除非在当前目录中,否则模块导入失败 - Python3

时间:2017-06-16 14:16:59

标签: python facebook python-3.x python-module

我已经写了一个小的Facebook OAUTH函数,每当我需要生成一个令牌发布到我的FB提要或页面时,我想用它作为模块。问题是除非我在fb_auth所在的目录中,否则我无法调用该模块。

这是我的代码:

#!/usr/bin/env python3

''' Facebook authorization module'''

import requests
import os

def get_token(app_id, app_secret):
    payload = {'grant_type': 'client_credentials', 'client_id': app_id, 'client_secret': app_secret}
    response = requests.post('https://graph.facebook.com/oauth/access_token?', params=payload)
    result = eval(response.text)
    token = result['access_token']
    return token


if __name__ == '__main__':

    get_token()

所以,当我在工作目录(/home/scripts/python/fb_auth/)时,模块将导入并按照预期运行:

>>> from fb_auth import get_token
>>> import os
>>> home = os.environ['HOME']
>>> work = home + '/scripts/python/'
>>> keys = work + 'apikeys'
>>> with open (keys, 'r') as f:
...    keys = eval(f.read())
... 
>>> app_id = keys['fb_keys']['riverwarn']['app_id']
>>> app_secret = keys['fb_keys']['riverwarn']['app_secret']
>>> get_token(app_id, app_secret)
'194XXXXXXXXXXXXXXXXXXXXXXXXXXXY_OM'

但是,如果我不在工作目录(/home/scripts/python/),我什么也得不到:

>>> import fb_auth
>>> fb_auth.get_token(app_id, app_secret)

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'fb_auth' has no attribute 'get_token'

>>> from fb_auth import get_token

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: cannot import name 'get_token'

我是否需要将其放在 Python模块文件夹中才能使其正常工作?

1 个答案:

答案 0 :(得分:1)

它不会找到它,因为它不会出现在sys.path中。 您可以通过安装将其添加到sys.path中。 请参阅此处的完整文档:https://docs.python.org/2/install/#how-installation-works