Package doesn't work if run from cmd or from the .py file… PYTHON

杀马特。学长 韩版系。学妹 提交于 2021-01-29 07:47:45

问题


I noticed a problem with python (windows). If I create a program (even simple) and I import a package, it works if I run it from the python shell but if I run it from the .py file or with the cmd (C:\Python34\program.py) it doesn't.

Make it clear:

Program 1

from selenium import webdriver
print("have a good day")

Program2

import pyautogui
print("be happy")
pyautogui.moveT(300,300)

Error program 1

Traceback (most recent calls)
 File"C:\Python34\program.py" line 1, in <module>
  from selenium import webdriver
ModuleNotFoundError: No module named 'selenium'

Error Program 2

Traceback (most recent calls)
 File"C:\Python34\program.py" line 1, in <module>
  import pyautogui
ModuleNotFoundError: No module named 'pyautogui'

So I don't understand why it doesn't find/recognize the module if I doesn't run it from the shell.


回答1:


The ModuleNotFoundError states that the module 'selenium' and 'pyautogui' isn't available for the python interpreter (the one you invoked to execute your script with). Since you have tried executing the same code from within the shell interpreter, the problem might be because of having multiple python installations on your Windows system.

When you have multiple versions of python installed on your system, then there is a possibility that the package(s) you tried installing using pip command doesn't end up residing inside the python version you were expecting them to be in.

Before you do anything, check which python version the pip utility is referring to:

$ pip --version pip <ver> from path/to/pip (python <version>)

If the python version at the end of the above result is 2.x, then it means that the selenium package you tried installing using pip install selenium ended up inside python 2 environment.

However, when you try to execute the python script, the 3.x interpreter is being invoked. In which case, the module will not be available. Here's what you can do:

Install package using pip3 command:

pip3 install selenium

This will install the selenium or any other package, inside python 3 installation only. Now you should be able to execute the script without any errors. Same goes for pyautogui.

Also, note that under Microsoft Windows, the python command usually invokes the Python 2 shell interpreter. In which case, you were easily able to run your code (which required selenium) without any errors. There is another utility called py, under Windows. You can learn more about that here

EDIT: selenium is not a pre-installed package



来源:https://stackoverflow.com/questions/53672940/package-doesnt-work-if-run-from-cmd-or-from-the-py-file-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!