반응형
반응형

[python] Django  설치,  프로젝트 생성

 

 

django-admin 명령어를 실행하려고 했을 때 시스템이 해당 명령어를 찾지 못하는 경우 발생합니다. 일반적으로 Django가 설치되어 있지 않거나, 설치 경로가 시스템의 환경 변수에 추가되지 않은 경우입니다.

해결 방법

1. Django가 설치되어 있는지 확인

  • 다음 명령어로 Django가 설치되어 있는지 확인합니다:
     
    pip show django
    • Django 버전과 경로가 출력되면 설치가 되어 있는 상태입니다.
    • 아무 내용도 출력되지 않으면 Django가 설치되지 않은 상태입니다. 이 경우, 다음 명령어로 설치하세요:
       
      pip install django

2. django-admin 명령어를 전체 경로로 실행

  • 가상환경 또는 시스템 경로 문제로 인해 django-admin이 실행되지 않을 수 있습니다. 전체 경로로 실행해보세요:
     
    python -m django --version
    또는
     
    python -m django startproject myproject

3. PATH 환경 변수 확인

  • django-admin 명령어가 시스템의 환경 변수 PATH에 등록되지 않았을 가능성이 있습니다.
  • Django 명령어가 있는 경로를 확인합니다:
     
    where django-admin
    또는
     
    where django-admin.exe
    • 경로가 출력되면, 해당 경로를 확인하고 PATH에 추가해야 할 수 있습니다.
    • 경로가 출력되지 않으면 Django가 설치되지 않았거나, 가상환경을 활성화하지 않은 상태일 수 있습니다.

4. 가상환경 활성화

  • 가상환경을 사용하는 경우, 먼저 활성화해야 Django 명령어를 사용할 수 있습니다.
    • Windows:
       
      .\venv\Scripts\activate
    • macOS/Linux:
       
      source venv/bin/activate
  • 활성화 후 다시 django-admin 명령어를 실행합니다:
    •  django-admin startproject myproject

5. Django 명령어를 실행할 Python 버전 확인

  • 시스템에 Python 2와 Python 3이 함께 설치되어 있는 경우, django-admin 명령어가 제대로 연결되지 않을 수 있습니다.
  • Python 3로 명시적으로 실행해보세요:
     
    python3 -m django startproject myproject

예시: 새 프로젝트 시작하기

  1. 가상환경 생성 및 활성화:
  2.  
    python -m venv venv source venv/bin/activate # Windows는 venv\Scripts\activate
  3. Django 설치:
  4.  
    pip install django
  5. 새 프로젝트 생성:
  6.  
    django-admin startproject myproject

여전히 문제를 해결하지 못한 경우

  1. Python 및 Django 설치 상태를 확인하세요:
     
    python --version pip show django
     
     
     
     

반응형
반응형

파일 선택 창을 띄워 파일을 선택하고, 선택한 파일을 읽어서 내용을 출력하는 PyQt5 프로그램입니다. 파일 선택 창은 QFileDialog를 사용합니다.

선택한 파일이 엑셀 파일(.xlsx, .xls)인 경우, 엑셀 내용을 시트별로 읽어와 화면에 출력하고, 텍스트 파일인 경우 텍스트 내용을 그대로 보여주는 PyQt5 프로그램입니다.

엑셀 파일 처리를 위해 openpyxl 또는 pandas 라이브러리를 사용할 수 있습니다. 여기서는 pandas를 이용합니다.

 

 

 

import sys
import os
import pandas as pd
from PyQt5.QtWidgets import (
    QApplication, QWidget, QVBoxLayout, QPushButton, QLabel, QFileDialog, QTextEdit
)


class FileHandlerApp(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        # 윈도우 설정
        self.setWindowTitle("File Handler App")
        self.setGeometry(100, 100, 800, 600)

        # 레이아웃 설정
        layout = QVBoxLayout()

        # 파일 선택 버튼
        self.select_button = QPushButton("Select File", self)
        self.select_button.clicked.connect(self.select_file)
        layout.addWidget(self.select_button)

        # 파일 경로 표시
        self.file_path_label = QLabel("No file selected", self)
        layout.addWidget(self.file_path_label)

        # 파일 내용 표시
        self.file_content = QTextEdit(self)
        self.file_content.setReadOnly(True)
        layout.addWidget(self.file_content)

        # 레이아웃 적용
        self.setLayout(layout)

    def select_file(self):
        # 파일 선택 창 띄우기
        options = QFileDialog.Options()
        options |= QFileDialog.ReadOnly
        file_path, _ = QFileDialog.getOpenFileName(
            self, "Select File", "", "All Files (*);;Excel Files (*.xlsx *.xls);;Text Files (*.txt)", options=options
        )

        if file_path:
            # 선택한 파일 경로 표시
            self.file_path_label.setText(f"Selected File: {file_path}")

            # 파일 확장자 확인
            _, file_extension = os.path.splitext(file_path)

            # 파일 처리
            if file_extension in [".xlsx", ".xls"]:
                self.read_excel(file_path)
            elif file_extension == ".txt":
                self.read_text(file_path)
            else:
                self.file_content.setText("Unsupported file type. Please select an Excel or text file.")

    def read_text(self, file_path):
        """텍스트 파일을 읽어와 화면에 표시"""
        try:
            with open(file_path, 'r', encoding='utf-8') as file:
                content = file.read()
                self.file_content.setText(content)
        except Exception as e:
            self.file_content.setText(f"Error reading file: {str(e)}")

    def read_excel(self, file_path):
        """엑셀 파일을 읽어와 화면에 표시"""
        try:
            excel_data = pd.ExcelFile(file_path)  # 엑셀 파일 읽기
            content = "Excel File Content:\n\n"

            # 시트별로 데이터 읽기
            for sheet_name in excel_data.sheet_names:
                content += f"Sheet: {sheet_name}\n"
                sheet_data = excel_data.parse(sheet_name).head(10)  # 각 시트의 첫 10행 읽기
                content += sheet_data.to_string(index=False)
                content += "\n\n"

            self.file_content.setText(content)
        except Exception as e:
            self.file_content.setText(f"Error reading Excel file: {str(e)}")


# 프로그램 실행
if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = FileHandlerApp()
    window.show()
    sys.exit(app.exec_())
반응형
반응형

[python] Django 설치

 conda create -n p_django python=3.11

 

 

Django 설치 확인

 python -m django --version

반응형
반응형

 

프로젝트를 다른 시스템(예: 동료 개발자의 컴퓨터 또는 배포 서버)으로 옮길 때, 동일한 파이썬 버전과 패키지를 정확히 맞춰야 하는 번거로움이 있습니다. 가상환경 내 설치된 패키지 목록을 requirements.txt로 저장하고, 이를 다른 환경에서 설치하면 동일한 실행 환경을 쉽게 재현할 수 있습니다.

현재 가상환경 패키지 목록 저장하려면 다음과 같이 실행합니다.

pip freeze > requirements.txt

다른 환경에서 패키지를 설치하려면 다음과 같이 실행합니다.

pip install -r requirements.txt

 

 

반응형
반응형

[python] Scatter plot animated using python, ffmpeg

 

""" 
An animated scatter plot can be created using Python's matplotlib library with its animation module. 
Here's an example of how to create an animated scatter plot, where points move dynamically over time.
"""

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

# Generate random initial data for the scatter plot
num_points = 50
x_data = np.random.rand(num_points)
y_data = np.random.rand(num_points)
colors = np.random.rand(num_points)
sizes = np.random.rand(num_points) * 100

# Function to update scatter plot
def update(frame):
    global x_data, y_data
    x_data += (np.random.rand(num_points) - 0.5) * 0.1  # Randomly move x
    y_data += (np.random.rand(num_points) - 0.5) * 0.1  # Randomly move y
    scatter.set_offsets(np.c_[x_data, y_data])  # Update positions
    scatter.set_sizes(np.random.rand(num_points) * 100)  # Update sizes
    scatter.set_array(np.random.rand(num_points))  # Update colors
    return scatter,

# Create the figure and scatter plot
fig, ax = plt.subplots()
scatter = ax.scatter(x_data, y_data, c=colors, s=sizes, cmap='viridis', alpha=0.6)
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
ax.set_title("Animated Scatter Plot")

# Create animation
ani = FuncAnimation(fig, update, frames=100, interval=50, blit=True)

# Show the animation
plt.show()

import matplotlib.animation as animation
animation.FFMpegWriter = animation.writers['ffmpeg']

""" 
Install FFmpeg: FFmpeg is required to save animations in video formats like .mp4. Install it as follows:

Windows:

Download the FFmpeg executable from https://ffmpeg.org/download.html.
Add the bin folder to your system’s PATH environment variable.

1.EXE  파일 다운받아서  *.7z 파일 다운로드. 

2.압축 풀고,  시스템 환경 변수에 추가. 

3.  ffmpeg -version  으로 실행되는지 확인 

"""

ani.save("animated_scatter.mp4", writer="ffmpeg", fps=30)  # Save as MP4

반응형
반응형
""" 
정렬 알고리즘 실행 시 비용 계산은 보통 실행 시간(시간 복잡도)이나 작업 횟수를 측정하여 이뤄집니다. 

이를 위해 Python에서 time 모듈이나 timeit 모듈을 사용할 수 있습니다. 

시간 복잡도에 따른 차이

1.퀵 정렬:
    평균 시간 복잡도 𝑂(𝑛log⁡𝑛)O(nlogn).
    큰 데이터셋에서도 효율적으로 작동.

2.버블 정렬:
    최악 및 평균 시간 복잡도 𝑂(𝑛2)O(n 2 ).
    작은 데이터셋에서는 괜찮지만, 데이터 크기가 클수록 비효율적.
    
"""
import time  # 실행 시간 측정을 위한 모듈

# 퀵 정렬 알고리즘
def quick_sort(arr):
    if len(arr) <= 1:
        return arr
    pivot = arr[len(arr) // 2]
    left = [x for x in arr if x < pivot]
    middle = [x for x in arr if x == pivot]
    right = [x for x in arr if x > pivot]
    return quick_sort(left) + middle + quick_sort(right)

# 버블 정렬 알고리즘
def bubble_sort(arr):
    n = len(arr)
    for i in range(n):
        for j in range(0, n - i - 1):
            if arr[j] > arr[j + 1]:
                arr[j], arr[j + 1] = arr[j + 1], arr[j]
    return arr

# 테스트 데이터 생성
import random
array_size = 1000  # 데이터 크기
test_array = random.sample(range(1, 10000), array_size)


print(f" test_array : {test_array} \n\n\n")

# 퀵 정렬 실행 시간 측정
start_time = time.time()
quick_sort(test_array.copy())
end_time = time.time()
print(f"퀵 정렬 실행 시간: {end_time - start_time:.5f}초")

# 버블 정렬 실행 시간 측정
start_time = time.time()
bubble_sort(test_array.copy())
end_time = time.time()
print(f"버블 정렬 실행 시간: {end_time - start_time:.5f}초")


# 병합 정렬 알고리즘
def merge_sort(arr):
    if len(arr) <= 1:
        return arr
    mid = len(arr) // 2
    left = merge_sort(arr[:mid])
    right = merge_sort(arr[mid:])
    return merge(left, right)

def merge(left, right):
    result = []
    i = j = 0
    while i < len(left) and j < len(right):
        if left[i] < right[j]:
            result.append(left[i])
            i += 1
        else:
            result.append(right[j])
            j += 1
    result.extend(left[i:])
    result.extend(right[j:])
    return result

# 병합 정렬 실행 시간 측정
start_time = time.time()
merge_sort(test_array.copy())
end_time = time.time()
print(f"병합 정렬 실행 시간: {end_time - start_time:.5f}초")

[python] 정렬 알고리즘 실행 시 비용 계산은 보통 실행 시간(시간 복잡도)이나 작업 횟수를 측정

 

 

 

반응형

+ Recent posts