본문 바로가기

Contact 日本語 English

【Python】 파이썬 주요 트러블슈팅 [41-60]

 

파이썬 주요 트러블슈팅 [41-60]

 

추천글 : 【Python】  파이썬 목차 


 

41. ImportError: cannot import name 'mnist.data_utils'

(grammar) 문제 상황

 

from mnist.data_utils import load_data

...

MNIST_data = h5py.File("mnist/MNISTdata.hdf5", 'r')

 

(grammar) 해결책 1. MNIST 데이터를 다운받은 뒤 다음과 같이 코드를 실행  

 

MNIST_data = h5py.File("./MNISTdata.hdf5", 'r')

X_train = np.float32(MNIST_data['x_train'][:])
y_train = np.int32(np.array(MNIST_data['y_train'][:, 0])).reshape(-1, 1)
X_test = np.float32(MNIST_data['x_test'][:])
y_test = np.int32(np.array(MNIST_data['y_test'][:, 0])).reshape(-1, 1)

MNIST_data.close()

 

 (grammar) 해결책 2. tensorflow.keras.datasets.mnist.load_data()를 활용

 

import tensorflow as tf

(Xtr, Ytr), (Xte, Yte) = tf.keras.datasets.mnist.load_data()

 

 

42. TypeError: can't multiply sequence by non-int of type 'float'

(grammar) 문제 상황 : 정수만 곱할 수 있는 상황에서 실수값을 곱한 경우

 

### case 1. (Good)
names = ("John ", "Jane ")
print(names * 2)
# ('John ', 'Jane ', 'John ', 'Jane ')

### case 2. (Bad)
names = ("John ", "Jane ")
print(names * 2.0)
# TypeError: can't multiply sequence by non-int of type 'float'

### case 3. (Good)
names = ("John ", "Jane ")
print(names * int(2.0))
# ('John ', 'Jane ', 'John ', 'Jane ')

 

레퍼런스 

 

TypeError: can't multiply sequence by non-int of type 'float' [SOLVED]

When coding, you're likely to encounter errors. Error messages, in most cases, help you understand what the error is about. And understanding an error message is one of the steps in solving an error. In this article, we'll talk about an error in Python –

www.freecodecamp.org

 

 

43. UnicodeDecodeError: 'utf-8' codec can't decode byte 0xdf in position 991: invalid continuation byte

(grammar) 문제점 발생 : data = pandas.read_csv('example.csv', index_col=0)

① 이때 α, β 같은 문자가 .csv 파일 안에 있어서 문제가 생겼던 것으로 추정하고 있음

(grammar) 해결책 : data = pandas.read_csv('example.csv', index_col=0, encoding='ISO-8859-1')

레퍼런스 

 

"for line in..." results in UnicodeDecodeError: 'utf-8' codec can't decode byte

Here is my code, for line in open('u.item'): # Read each line Whenever I run this code it gives the following error: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 2892: inv...

stackoverflow.com

 

 

44. Server Connection Error: A connection to the Jupyter server could not be established. JupyterLab will continue trying to reconnect. Check your network connection or Jupyter server configuration. 

(system) 문제점 : jupyter lab, jupyter notebook 모두에서 같은 문제가 발생함

(others) 해결책 1. broken pipe 문제일 수도 있고, 이 경우 다음과 같이 해결

 

Broken Pipe 문제 해결

문제터미널에서 ssh로 서버 연결후 서버로 작업중 Broken pipe가 뜨면서 서버 연결이 끊긴다. 해결터미널에 nano ~/.ssh/config 입력하여 text editor를 실행한다. 참고로 "config" 가 있는 위치(/etc/ssh/ssh_config

may0301.tistory.com

① broken pipe는 국가 보안정책상 네트워크 체계가 당연히 갖춰야 함

② VPN 등으로 사용자에게 broken pipe 문제가 일어나지 않도록 할 수 있음

(others) 해결책 2. 실행이 오래 걸리는 경우 오랫동안 클라이언트가 서버에 응답하지 않아 서버에서 connection을 일부러 끊는 경우가 있음. 이 경우 jupyter notebook / jupyter lab을 생성한 anaconda prompt 혹은 terminal에 주기적으로 엔터(Enter)를 쳐 주어 클라이언트의 무응답 문제 및 connection error를 해결할 수 있음    

 

 

45. No module named 'google.protobuf'

 (system) 해결책 : conda install protobuf

 

 

46. error: OpenCV(4.6.0) /io/opencv/modules/imgproc/src/color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cvtColor'

(grammar) opencv로 파일을 읽을 적에 이미지 파일이 존재하지 않는 경우

 

 

47. RuntimeError: CUDA error: out of memory

(system) 원인 : GPU usage가 한도를 넘어간 경우

(system) 해결방법 : python app.py와 같은 명령어를 다음과 같이 변경

① 의미 : 다른 테스크가 0번 GPU을 쓰고 있는 경우, 이번 테스크에 1번 GPU를 사용하겠다고 별도로 명시

 

CUDA_VISIBLE_DEVICES=1 python app.py

 

 

48. RuntimeError: CUDA error: no kernel image is available for execution on the device

(package) 원인 : torch 및 torchvision의 버전이 시스템 (e.g., 서버, 워크스테이션) 조건과 안 맞는 경우 

① 가령, RTX3090은 CUDA11 이상을 사용하여야 함

관련 오류 메시지 : The current PyTorch install supports CUDA capabilities sm_37 sm_50 sm_60 sm_70. If you want to use the NVIDIA GeForce RTX 3090 GPU with PyTorch, please check the instruction.

(package) 해결방법 : 단순히 pip install torch, pip install torchvision이 아니라 다음과 같이 설치하여야 함 (ref.

 

pip install torch==1.7.1+cu110 torchvision==0.8.2+cu110 -f https://download.pytorch.org/whl/torch_stable.html

 

 

49. ImportError: cannot import name 'ctx' from 'dash'

(package) 해결방법 : dash package의 버전을 2.3.1에서 2.9.3으로 업그레이드 (필자 기준)

 

 

50. AttributeError: 'Flask' object has no attribute 'before_first_request'

(package) 해결방법 : dash package의 버전을 2.3.1에서 2.9.3으로 업그레이드 (필자 기준)

 

 

51. ImportError: cannot import name 'cached_property' from 'werkzeug'

(package) 해결책 : Werkzeug >= 1.0 버전을 down-grade 

 

pip uninstall Werkzeug
pip install Werkzeug==0.16.0

 

레퍼런스 

 

문제 해결 공유 Flask Werkzeug (ImportError: cannot import name 'cached_property' from 'werkzeug' (C:\Users\lodics\anaconda

(ImportError: cannot import name 'cached_property' from 'werkzeug' (C:\Users\lodics\anaconda3\lib\site-packages\werkzeug\__init__.py)) 간만에 로컬 환경에서 개발할려고하니까 위 문제 가 발생하였다.... 공부좀 할려고하면 맨

edudeveloper.tistory.com

 

 

52. TypeError: expected str, bytes or os.PathLike object, not numpy.ndarray

 (grammar) 문제 상황 : gseapy.enrichr를 쓰는 상황에 ar = array(['RBMS3', 'PDE5A', dtype=object)를 gene_list 자리의 입력으로 넣어주었을 때 문제가 발생함

(grammar) 원인 : numpy.ndarray 자료형을 입력으로 넣을 게 아니라 list 자료형으로 넣어야 함

(grammar) 해결방법 : numpy.ndarray.tolist(ar) 또는 ar.tolist()를 입력으로 넣어주어야 함 

 

 

53. OSError: wkhtmltopdf exited with non-zero code 1. error: qt.qpa.screen: QXcbConnection: Could not connect to display Could not connect to any X display.

(grammar) 문제 상황 

 

pdfkit.from_string(output_text, 'pdf_generated.pdf', configuration=config)

 

(grammar) 해결방법

 

# newly added
from pyvirtualdisplay import Display
display = Display()
display.start()

# previous
pdfkit.from_string(output_text, 'pdf_generated.pdf', configuration=config)

# newly added
display.stop()

 

레퍼런스 

 

wkhtmltopdf (pdfkit) Could not connect to any X display

I am trying to use wkhtmltopdf with Django ,nginx,uwsgi it works perfectly on development env running using manage.py runserver but when serving with nginx ans uwsgi i get this error: wkhtmltopdf

stackoverflow.com

 

 

54. FileNotFoundError: [Errno 2] No such file or directory: 'Xvfb'

(package) 해결방법 : Xvfb 패키지 설치 (ref) (failed

 

sudo apt-get install xvfb
pip install xvfbwrapper

 

(grammar) 해결방법 : pyvirtualdisplay를 사용하지 않기 (success)

 

# before
...
from pyvirtualdisplay import Display
display = Display()
display.start()
pdfkit.from_string(output_text, 'my_pdf.pdf', configuration=config)
display.stop()

# after
...
pdfkit.from_string(output_text, 'my_pdf.pdf', configuration=config)

 

 

55. TypeError: import_optional_dependency() got an unexpected keyword argument 'errors'

(grammar) 해결방법 : pip install pandas --upgrade

레퍼런스

 

TypeError: import_optional_dependency() got an unexpected keyword argument 'errors'

I am trying to work with Featuretools to develop an automated feature engineering workflow for the customer churn dataset. The end outcome is a function that takes in a dataset and label times for

stackoverflow.com

 

 

56. bash: java: command not found

(package) 해결방법 (ref)

 

sudo apt install default-jre

 

 

57. Error: LinkageError occurred while loading main class picard.cmdline.PicardCommandLine java.lang.UnsupportedClassVersionError: picard/cmdline/PicardCommandLine has been compiled by a more recent version of the Java Runtime (class file version 61.0), this version of the Java Runtime only recognizes class file versions up to 55.0

(package) 원인 : picard 버전이 Java 17 (ver. 61.0)이었는데 내 시스템은 Java 11 (ver. 55.0)이었던 경우 

 (package) 해결책 : picard를 downgrade. 천천히 버전을 내려 가면서 테스트하면 해결할 수 있음  

 

 

58. Assertion failure in +[NSUndoManager _endTopLevelGroupings], NSUndoManager.m:1117

(system) 원인 : 파이썬의 여러 thread가 동시에 macOS GUI에 액세스 하려고 시도할 때 tread-safety conflict 때문에 생기는 것으로 추정

(system) 해결책 1. 맥북 환경이 아니라 리눅스 환경에서 실행

(grammar) 해결책 2. 웹서버의 interactive mode가 이 문제를 일으킬 수 있는데, 이 경우 이를 disable 함으로써 해결할 수도 있음

 

import matplotlib
matplotlib.use('Agg')

 

 

59. ImportError: cannot import name 'Int64Index' from 'pandas'

(package) 해결방법 : pandas 및 xgboost 재설치 (ref)

 

pip uninstall pandas
pip install pandas --upgrade
pip3 uninstall xgboost
pip3 install xgboost

 

 

60. E: Unable to locate package tree

(package) 해결방법

 

sudo apt-get install update
sudo apt-get install tree

 

입력: 2023.01.28 02:15

수정: 2023.07.28 17:22