简体   繁体   中英

Module found on python shell / interactive prompt, but getting ModuleNotFound on import in file

I am trying to use python-twitter ( https://python-twitter.readthedocs.io/en/latest/index.html ), and I am not having much luck. The python-twitter module is invoked with import twitter , unfortunately when I attempt to do that via my script from the command line it isn't working.

What's boggling my mind, is that there is no similar error when executing from the python shell.

Everything is installed correctly, it would seem:

(venv) user@computer:~/Documents/projectdir$ pip3 install python-twitter
Requirement already satisfied: python-twitter in /home/user/.local/lib/python3.8/site-packages (3.5)
Requirement already satisfied: requests-oauthlib in /home/user/.local/lib/python3.8/site-packages (from python-twitter) (1.3.0)
Requirement already satisfied: requests in /usr/lib/python3/dist-packages (from python-twitter) (2.22.0)
Requirement already satisfied: future in /usr/lib/python3/dist-packages (from python-twitter) (0.18.2)
Requirement already satisfied: oauthlib>=3.0.0 in /usr/lib/python3/dist-packages (from requests-oauthlib->python-twitter) (3.1.0)

(venv) user@computer:~/Documents/projectdir$ pip3 install twitter
Requirement already satisfied: twitter in /home/user/.local/lib/python3.8/site-packages (1.18.0)


(venv) user@computer:~/Documents/projectdir$ pip3 freeze > requirements.txt

(venv) user@computer:~/Documents/projectdir$ echo "$(<requirements.txt)"
...
python-twitter==3.5
...
twitter==1.18.0
...

And yet my script throws an error:

(venv) user@computer:~/Documents/projectdir$ sudo python3 authentication_test.py
Traceback (most recent call last):
  File "authentication_test.py", line 1, in <module>
    import twitter
ModuleNotFoundError: No module named 'twitter'

Despite the twitter module being found by the python shell:

(venv) user@computer:~/Documents/projectdir$ python3
Python 3.8.5 (default, Jul 28 2020, 12:59:40) 
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import twitter
>>> twitter.Api()
<twitter.api.Api object at 0x7f11b0056a60>
>>> 

What's going on here? I thought maybe there was something causing issues between twitter and python-twitter , but I did pip3 uninstall twitter and the issue persists.

I should note that although I broke them up with comments, the above code snippets were done consecutively.

Ideas?

As stated by Aaron (thank you), the answer was that sudo was taking me out of the virtualenv context, and thus the packages were not available.

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