Can't Import Modules Python 3 Windows - python

Problem Description: When running scripts from the terminal (example: navigate to C:\PythonPrograms\ProjectName> and input file name so it looks like C:\PythonPrograms\ProjectName>main.py), the script fails to run and an error message is received. For example, if a script includes import numpy, the error is ImportError: No module named numpy. When running from an IDE such as spyder, modules import correctly.
Modules were installed with Anaconda, and appear under C:\Python37\Lib\site-packages
Systems: Windows 10, Python 3.7.0
Code examples
This script successfully runs:
x = 1
for i in range(10):
print x
x += 1
C:\Python Programs>test.py
1
2
3
4
5
6
7
8
9
10
This script does not run:
import serial
x = 1
for i in range(10):
print x
x += 1
C:\Python Programs>test.py
Traceback (most recent call last):
File "C:\Python Programs\test.py", line 1, in <module>
import serial
ImportError: No module named serial
Edit:
Python is added to the system path as shown:Screenclip
Solved!
Checked the path, it was all correct. Went to uninstall python and reinstall, discovered that there was an unknown python 2.7 installed, once it was uninstalled everything worked correctly.

You have to make sure that your Python Path Environment Variable is correctly set on your system.
This should look like
C:\Users\YOUR_USERNAME\AppData\Local\Programs\Python\Python37-32\
If it don't, try to reinstall Python and check Add Python 3.7 to PATH

Related

ImportError Python cannot import name

I am trying to reproduce a code from a scientific publication which uses Python 2:
https://github.com/TeamErlich/dna-fountain
The code is based on Python 2 so I had to change my environment to Python 2 from Python 3. Anyways, when I ran the code I realized that Python is not able to import DNAFountain from fountain, although I successfully installed it with pip install fountain. I constantly receive this error message:
File "encode.py", line 9, in <module>
from fountain import DNAFountain
ImportError: cannot import name DNAFountain
Does anybody know why my code is not able to import DNAFountain?

Python not recognized in CMD

I am working in Windows 11, Python 3.10, Mu 1.1.0. I followed the instructions on ATBS to create a batch file to run a script from the WIN + R launcher. However in CMD the error A(below) pops up. I tried following instructions from the documentation on python.org, and in Appendix B of ATBS to edit environment variables. I added the following to PATH env variables: C:\Users\19139\MyPythonScript; C:\Users\19139\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Python 3.10\Python 3.10 (64-bit).lnk; and C:\Users\19139\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Python 3.10\Python 3.10 (64-bit).lnk\Scripts. Is there some issue with the fact that the PATH includes start menu? All I am able to call from CMD is py --version. When I try and directly call a python script I get Error B. I disabled the "App Installer"(s) under App Aliases for Python.exe and Python3.exe but no change in error. I can call py --version, but I am beyond the scope of my ability to figure out what to do. I am unsure of next possible step to problem solve, suggestions welcome.
Error A:
`enter code here`Python path configuration:
PYTHONHOME = (not set)
PYTHONPATH = (not set)
program name = 'C:\Users\19139\AppData\Local\Programs\Python\Python310\python.exe'
isolated = 0
environment = 1
user site = 1
import site = 1
sys._base_executable = 'C:\\Users\\19139\\AppData\\Local\\Programs\\Python\\Python310\\python.exe'
sys.base_prefix = ''
sys.base_exec_prefix = ''
sys.platlibdir = 'lib'
sys.executable = 'C:\\Users\\19139\\AppData\\Local\\Programs\\Python\\Python310\\python.exe'
sys.prefix = ''
sys.exec_prefix = ''
sys.path = [
'C:\\Users\\19139\\AppData\\Local\\Programs\\Python\\Python310\\python310.zip',
'C:\\Users\\19139\\AppData\\Local\\Programs\\Python\\Python310\\Lib\\',
'C:\\Users\\19139\\AppData\\Local\\Programs\\Python\\Python310\\DLLs\\',
'C:\\Users\\19139\\AppData\\Local\\Programs\\Python\\Python310',
]
Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding
Python runtime state: core initialized
Traceback (most recent call last):
File "C:\Users\19139\AppData\Local\Programs\Python\Python310\Lib\encodings\__init__.py", line 31, in <module>
ModuleNotFoundError: No module named 'codecs'
Error B
C:\Users\19139>python "C:\Users\19139\MyPythonScript\mClip.py"
Python was not found; run without arguments to install from the Microsoft Store, or
disable this shortcut from Settings > Manage App Execution Aliases.
First of all, unlike ubuntu/ linux Windows doesn't detect python on its own. That's why we need to specify the path manually, to make it aware of python.
Is there some issue with the fact that the PATH includes start menu?
Yes, there is issue there. PATH for python doesn't include Start Menu generally.
You are looking at the wrong place or have installed python package at the wrong location. Find the correct python package location.
Python PATH looks something like this:
C:\Users\user_name\python_installerpkg_name
For example, if you have installed python using a python installer pkg like anaconda/ mini-conda, you can use its command prompt to find the location via where python. Then use the location to set the PATH in environment variables. the PATH would look like: C:\Users\user_name\anaconda
Error B
Until you configure the correct path in the environment variables you won't be able to use the command python filename.py from the command line.

I am struggling to import "wmi" in visual studio code

i am using py 3.6 and whenever i type this:
import wmi
def avg(value_list):
num = 0
length = len(value_list)
for val in value_list:
num += val
return num/length
w = wmi.WMI(namespace=r"C:\Users\name\Desktop\OpenHardwareMonitor")
sensors = w.Sensor()
cpu_temps = []
gpu_temp = 0
for sensor in sensors:
if sensor.SensorType==u'Temperature' and not 'GPU' in sensor.Name:
cpu_temps += [float(sensor.Value)]
elif sensor.SensorType==u'Temperature' and 'GPU' in sensor.Name:
gpu_temp = sensor.Value
print("Avg CPU: {}").format(avg(cpu_temps))
print("GPU: {}").format(gpu_temp)
it comes out as:
PS C:\Users\name> & C:/Users/name/AppData/Local/Programs/Python/Python36/python.exe "c:/Users/name/gpu temps.py"
Traceback (most recent call last):
File "c:/Users/name/pip install gpiozero.py", line 1, in <module>
import wmi
ModuleNotFoundError: No module named 'wmi'
i went through alot of the options on the web and 1 other post and went through all the options, including " pywin32-300.win-amd64-py3.6.exe" on https://github.com/mhammond/pywin32/releases...
still doesnt work
In regards to the details given in the comments.
What I would generally suggest is to create virtual environments for each python project you have.
in visual studio code here is how you could do it:
Open your project folder with VS-Code
open the terminal inside VS-Code
execute C:\Users\name\AppData\Local\Programs\Python\Python36\python.exe -m venv env (or the path to your python installation you'd like to create a virtual environment of)
activate your enviornment by entering . .\env\Scripts\Activate.ps1 (assuming windows, you might need to enter Set-ExecutionPolicy Unrestricted -Scope Process to allow execution
now you should have a little (env) shown in the terminal, indicatung you're using the virtual environment.
next you can enter all the pip install commands you need for your project.

Pyinstaller - ModuleNotFoundError: No module named 'cpuinfo' [duplicate]

This question already has answers here:
Pyinstaller 'failed to execute' script
(2 answers)
Processes stuck in loop with PyInstaller-executable
(1 answer)
Closed 20 days ago.
I'm trying to package this script but I keep getting this error message
Traceback (most recent call last):
File "systeminfo.py", line 1, in <module>
ModuleNotFoundError: No module named 'cpuinfo'
[6308] Failed to execute script systeminfo
I tried this into cmd
pyinstaller -F --hidden-import="cpuinfo" systeminfo.py
I'm on the latest version of pyinstaller and pip.
This is the import section of my file:
import psutil, platform, GPUtil, cpuinfo, os, sys, wmi, winreg, getpass
from tabulate import tabulate
from datetime import datetime
When I run it, it just opens up and closes out. But when I run it through CMD, that's when I get that error message.
How do I fix this? I want to include all the modules so I can run this script on different computers that don't have python installed.
EDIT:
I fixed this issue by using this thread: Pyinstaller 'failed to execute' script
I use pycharm so this worked for me.
The only issue is whenever the CMD opens up, nothing happens. The only thing that can printed is if I hardcode a print(). Functions aren't working at all.
fix it with :
pip install py-cpuinfo

Installing OCRmyPDF on Windows Server 2016 - Can't find liblept.dll. Is editing Path safe?

I'm trying to import ocrmypdf on my company's client's Windows Server 2016 Build 14393 computer using Python 37-32. When I import the library, in a Jupyter Notebook, it is unable to locate leptonica by using ctypes.utility.find_library().
Ocrmypdf is a Linux-developed Python 3 package. Per the documentation (https://ocrmypdf.readthedocs.io/en/latest/introduction.html) it does not support Windows. The suggested workarounds are a docker container and Windows Subsystem for Linux.
I would rather not use a docker container as neither I nor my coworkers are very experienced with it. I am unable to use wsl as it is not available for my build of Windows Server 2016 (see the troubleshoot subsection: https://learn.microsoft.com/en-us/windows/wsl/install-on-server)
This discussion (find_library() in ctypes) states that you can point ctypes.utility.find_library to the needed library file by editing the environment Path variable to be a folder which includes it. Conveniently, Tesseract OCR's windows download includes liblept. Would editing the Path variable to point toward that folder be a dangerous thing to do?
Edit: I tried adding the path to Tesseract-OCR's folder on my laptop's environment Path and restarted Anaconda, etc. ocrmypdf still gave the same error.
A closer read of that discussion brought up the point that find_library operates differently on Windows. A read of the documentation (https://docs.python.org/2.5/lib/ctypes-finding-shared-libraries.html) states that "On Windows, find_library searches along the system search path, and returns the full pathname, but since there is no predefined naming scheme a call like find_library("c") will fail and return None." Does this mean I have to hardcode in a name to use in order to find the library?
This issue has been replicated, albeit on a different machine, here: https://github.com/jbarlow83/OCRmyPDF/issues/341. You can reproduce the issue by running the below code on a Windows machine.
!pip install ocrmypdf
import ocrmypdf
The expected result of the above code is that ocrmypdf is successfully imported in a usable form.
The result of the above code is:
OSError Traceback (most recent call last)
<ipython-input-2-a81f3474d7ad> in <module>
----> 1 import ocrmypdf
~\AppData\Local\Continuum\anaconda3\lib\site-packages\ocrmypdf\__init__.py in <module>
16 # along with OCRmyPDF. If not, see <http://www.gnu.org/licenses/>.
17
---> 18 from . import helpers, hocrtransform, leptonica, pdfa, pdfinfo
19 from ._version import PROGRAM_NAME, __version__
20 from .api import Verbosity, configure_logging, ocr
~\AppData\Local\Continuum\anaconda3\lib\site-packages\ocrmypdf\leptonica.py in <module>
40 logger = logging.getLogger(__name__)
41
---> 42 lept = ffi.dlopen(find_library('lept'))
43 lept.setMsgSeverity(lept.L_SEVERITY_WARNING)
44
OSError: cannot load library '<None>': error 0x57
I have been able to get this working Windows 10 by updating the path and it works fine. I used msys2 to install it, hence, the path name. Update to point where your liblept-5.dll is located.
if os.name == 'nt':
os.environ['PATH'] = os.environ.get("PATH", "") + ';C:\\msys64\\mingw64\\bin'

Categories