Byte 배열 형태의 정보를 보내고, 받을 때 접근 방식   

 

1) Network에서 16byte의 날짜 정보가 2byte 단위의 Byte Array로 전달되었을 때 받아들이기 

    dateData = client_socket.recv(16)

    wYear           = int.from_bytes(dateData[0:2], byteorder='little')
    wMonth          = int.from_bytes(dateData[2:4], byteorder='little')
    wDayOfWeek      = int.from_bytes(dateData[4:6], byteorder='little')
    wDay            = int.from_bytes(dateData[6:8], byteorder='little')
    wHour           = int.from_bytes(dateData[8:10], byteorder='little')
    wMinute         = int.from_bytes(dateData[10:12], byteorder='little')
    wSecond         = int.from_bytes(dateData[12:14], byteorder='little')
    wMilliseconds   = int.from_bytes(dateData[14:16], byteorder='little')

 

2) 시간 정보를 2byte단위로 잘라 byte Array에 담아 전송할 때.(수신 측의 Byte order는 Little이다.)

    current_time = datetime.now()

    sendData =int.to_bytes(current_time.year,           2, byteorder='little')
    sendData+=int.to_bytes(current_time.month,          2, byteorder='little')
    sendData+=int.to_bytes(current_time.weekday(),      2, byteorder='little')
    sendData+=int.to_bytes(current_time.day,            2, byteorder='little')
    sendData+=int.to_bytes(current_time.hour,           2, byteorder='little')
    sendData+=int.to_bytes(current_time.minute,         2, byteorder='little')
    sendData+=int.to_bytes(current_time.second,         2, byteorder='little')
    sendData+=int.to_bytes(int(current_time.microsecond/1000),   2, byteorder='little')

'작업 > Python' 카테고리의 다른 글

Python "exe" 실행 파일 만들기  (3) 2021.07.22
Python - 기본 문법 예제 (1)  (0) 2021.07.20
Visual Studio Python & Tensorflow 설치  (4) 2021.07.12

1) pyinstaller 설치

>> pip install pyinstaller

-->update 진행

 

2) 실행 위치

설치후 pyinstaller 위치

C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\Scripts

 

 

경로 입력 및 실행

Run_Py2Exe.BAT로 링크를 한 번에

(:주의) 일반 실행을 한다.(관리자 권한 실행을 하면 중간 경로가 "C:\Windows\System32"에 생기게 된다.)

::메인 UI Exe를 실행 해준다.
::주의) 일반 실행을 한다.(관리자 권한 실행을 하면 중간 경로가 "C:\Windows\System32"에 생기게된다.
echo off

::======== pyinstaller가 있는 경로 설정 ======== 
path=%path%;C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\Scripts;

::======== 만들어질 위치 대상과 목표파일 설정======== 
pyinstaller.exe -F -n PyNew.exe E:\Python\PythonApplication2\PythonApplication2\PythonApplication2.py

::======== 완료후 상태 점검을 위해
pause

 

이전 파일 제거 기능 추가.

::메인 UI Exe를 실행 해준다.
::주의) 일반 실행을 한다.(관리자 권한 실행을 하면 중간 경로가 "C:\Windows\System32"에 생기게된다.
echo off

::이전 파일 제거
rmdir /s /Q dist
rmdir /s /Q build
del *.exe.spec /s

::지우고 잠시 대기
timeout /t 2

::======== pyinstaller가 있는 경로 설정 ======== 
path=%path%;C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\Scripts;

::======== 만들어질 위치 대상과 목표파일 설정======== 
pyinstaller.exe -F -n PyNew.exe E:\Python\PythonApplication2\PythonApplication2\PythonApplication2.py

::======== 완료후 상태 점검을 위해
pause

 

 

3) 생성 옵션

pyinstaller --onefile 작업파이선파일.py

(pyinstaller --F 작업파이선파일.py)

 

pyinstaller --n 실행파일명.exe 작업파이선파일.py

 

pyinstaller --icon=파일아이콘.ico 작업파이선파일.py

 

pyinstaller --noconsole 작업파이선파일.py

(pyinstaller --w 작업파이선파일.py)

 

 

4) 동작 영상

 

 

'작업 > Python' 카테고리의 다른 글

Python byte Data 읽기/쓰기  (0) 2021.08.20
Python - 기본 문법 예제 (1)  (0) 2021.07.20
Visual Studio Python & Tensorflow 설치  (4) 2021.07.12

짧고 굵게 Python 경험하기~ㅎㅎ

byte_of_python.pdf (첨부파일 참고)

import os

import tensorflow as tf

print ("======================================================================")
#======================================================================
텐서 = tf.constant(3)
os.system('cls')
print(텐서)
print ("Hello World Python") #Note that print is a statement
print ("======================================================================")
#======================================================================
print("1) print 명령어 형태")

age = 45
name ="최지형"
print ("{0} was {1} Years Old when he wrote this book".format(name, age))
print ("{} was {} Years Old when he wrote this book".format(name, age))
print (name + " was " + str(age) + " Years Old when he wrote this book")

print ("float Value {0:.3f}".format(1.0/3))
print ("String Value {0:_^11}".format("Hello"))
print ("String Value {0:&^11}".format("Hello"))
print ("{name} wrote {book}".format(name="최지형", book="A Byte of Python"))

print("a",)                             # ,를사용하여 \n을 무시 시키는 기능이나 동작 하지 않음
print("b",)
print("abcdefghijklmnopqrstuvwxyz")
print("abcdefghijkl\nmnopqrstuvwxyz")   #\n으로 New Line 실행
print("abcdefghijkl\
mnopqrstuvwxyz")                        # \ 으로 다음라인과 이어짐을 나타낸다.
print(r"abcdefghijkl\nmnopqrstuvwxyz")  # r을 사용 하여 특수문자를 일반 문자로 표시

print ("======================================================================")
print("2) 변수 (대소문자 구분)")
i = 5
print (i)
i = i + 1
print (i)
s = """This is al multi-line string.
this is the second line"""
print (s)

print ("======================================================================")
print("3) 연산자와 수식")
length = 5
breadth = 2
area = length * breadth
print ('Area is', area)
print ('Perimeter is', 2 * (length + breadth))

print ("======================================================================")
print("4) 흐름 제어")

#number = 23
#guess = int(input('Enter an integer : '))
#if guess == number:
#    # New block starts here
#    print ('guess{} == Number{}, Congratulations, you guessed it.'.format(guess , number))  # New block ends here
#    print ('(but you do not win any prizes!)')
#elif guess < number:
#    # Another block
#    print ('guess{} > Number{}, it is a little higher than that'.format(guess , number))# You can do whatever you want in a block ...
#else:
#    print ('No, it is a little lower than that')
## you must have guessed > number to reach here
#print ('Done')

print ("-----------------------------------------------------------------------")
if True :
    print("Yes it is true")
print ("-----------------------------------------------------------------------")
#number = 25
#running = True
#while running:
#    guess = int(input('신규 수치를 입력 하세요 :'))
#    if guess == number:
#        print("입력 수치와 번호가 같습니다.")
#        running = False
#    elif guess<number:
#        print("입력 수치가 작습니다.")
#    else :
#        print("입력 수치가 큽니다.")
#else:
#    print("while 루프가 종료 됩니다.")
#print ('Done')
#print ("-----------------------------------------------------------------------")

print("i는 1부터 5미만 까지 출력")
for i in range(1, 5):
    print (i)
else:
    print("For 문의 동작 이 완료 되었습니다.")
print("i는 1부터2씩증가 하는 5미만 까지 출력")
for i in range(1, 5, 2):
    print (i)
else:
    print("For 문의 동작 이 완료 되었습니다.")

print("i는 리스트에 추가된 수치 만큼  대입 진행")
for i in [ 1, 3, 5, 7, 9, 10, 11, 12]:

    if i==5 :
        print("\t{}>=5임으로 continue를 통하여 다음으로 넘어 갑니다.".format(i))
        continue
    print (i)
    if i>=9 :
        print("\t{}>=9임으로 Break하여 종료 합니다.".format(i))
        break
else:
    print("For 문의 동작 이 완료 되었습니다.")


#while True:
#    s = input("임의의 글을 입력 하세요 :")
#    if s == "종료":
#        break
#    if len(s)<3:
#        print("너무 짧아요 ~~!!")
#        continue
#else:
#    print("while 문의 동작 이 완료 되었습니다.")

print ("======================================================================")
print("5) 함수")

print ("-----------------------------------------------------------------------")
def say_hello():
    #함수 내부 동작.
    print("Hello World")
#함수 종료.
print ("-----------------------------------------------------------------------")
#한글 함수, 인자 
def 출력_최대값(앞인자, 뒤인자):
    #함수 내부 동작.
    if 앞인자>뒤인자:
        print("{앞수}는 {뒤수}보다 크다".format(앞수=앞인자, 뒤수=뒤인자))
    elif 앞인자==뒤인자:
        print("{}는 {}와 같다".format(앞인자, 뒤인자))
    else:
        print("{}는 {}보다 작다".format(앞인자, 뒤인자))
#함수 종료.
print ("-----------------------------------------------------------------------")
#한글 함수, 인자 
def 출력_값바꾸기(앞인자, 뒤인자):
    #함수 내부 동작.
    print("\t함수내부")
    print("\t{앞수}, {뒤수} 변경전".format(앞수=앞인자, 뒤수=뒤인자))
    숫자바구니 = 앞인자
    앞인자 = 뒤인자
    뒤인자 = 숫자바구니
    print("\t{}, {} 변경후".format(앞인자, 뒤인자))
    return None
#함수 종료.
print ("-----------------------------------------------------------------------")
전역값 = 100
def 출력_전역값바꾸기(변경값인자):
    #함수 내부 동작.
    global 전역값
    print("\t함수내부")
    print("\t전역값{}, 변경값인자{} 변경전".format(전역값, 변경값인자))
    전역값 = 변경값인자
    print("\t전역값{} 변경후".format(전역값))
    return None
#함수 종료.

print ("-----------------------------------------------------------------------")

def 출력_기본값할당(인자1, 인자2=10, 인자3=20):
    #함수 내부 동작.
    global 전역값
    print("\t함수내부")
    print("\t인자1({}), 인자2({}), 인자3({})".format(인자1, 인자2, 인자3))
    return None
#함수 종료.
print ("-----------------------------------------------------------------------")


def 출력_가변인자(초기값 = 5, *입력수, **단어들):
    #DocString설정
    '''함수설명이나 정볼를 담고있다가
    출력요청이 있으면 출력을 해줍니다.
    
    추가적인내용은 이곳에 기술 합니다.'''

    #함수 내부 동작.
    count = 초기값
    for number in 입력수:
        count += number
    for key in 단어들:
        count += 단어들[key]

    if count<100:
        return "수치가 100보다 작습니다."
    else:
        print("수치가 100이상이군요")
    return count
#함수 종료.
print ("-----------------------------------------------------------------------")
def some_function():
    pass
print ("-----------------------------------------------------------------------")
say_hello() # 함수 호출 1
say_hello() # 함수 호출 2
print ("-----------------------------------------------------------------------")
출력_최대값(1, 2)
출력_최대값(2, 2)
출력_최대값(5, 2)
print ("-----------------------------------------------------------------------")
바뀔수_1 = 2
바뀔수_2 = 5
print("변경전 바뀔수_1({}), 바뀔수_2({})".format(바뀔수_1, 바뀔수_2))
출력_값바꾸기(바뀔수_1, 바뀔수_2)
print("변경후 바뀔수_1({}), 바뀔수_2({})".format(바뀔수_1, 바뀔수_2))
print ("-----------------------------------------------------------------------")
print("변경전 전역값({})".format(전역값))
출력_전역값바꾸기(5)
print("변경후 전역값({})".format(전역값))
출력_전역값바꾸기(99)
print("변경후 전역값({})".format(전역값))
print ("-----------------------------------------------------------------------")
출력_기본값할당(5)
출력_기본값할당(10, 99)
print ("-----------------------------------------------------------------------")
출력_기본값할당(5, 인자3=60)
출력_기본값할당(5, 인자3=45, 인자2=99)

print ("-----------------------------------------------------------------------")
#인자1 10, 리스트 [] (*)튜플 [1, 2, 3], (**)사전{vegetable=50, fruits= 100}로 함수에 전달.
print(출력_가변인자(10, 1, 2, 3, vegetable=50, fruits= 100))
print ("DocString:{}".format(출력_가변인자.__doc__))

print(출력_가변인자(10, 1, 2, 3, vegetable=10, fruits= 20))
help(출력_가변인자)
print ("-----------------------------------------------------------------------")
print(some_function())
print ("-----------------------------------------------------------------------")
print ("======================================================================")
print("6) 모듈")
#새로 만들 파일의 모듈을 추가 하자.
import module_Using_sys
#모듈 전체를 실행
module_Using_sys

module_Using_sys.sys_안녕()
print ("Version:{}".format(module_Using_sys.__version__))

print ("======================================================================")
print("7) 자료구조")
쇼핑리스트 =["사과", "망고", "수박", "바나나"]
print("구매목록은 {}개 입니다.".format(len(쇼핑리스트)))

번호 = 1
for 목록 in 쇼핑리스트:
    print("항목{}({})".format(번호,목록))
    번호+=1
print ("-----------------------------------------------------------------------")
쇼핑리스트.append("참외")
print("추가 구매목록은 {}개 입니다.".format(len(쇼핑리스트)))
쇼핑리스트.sort()
번호 = 1
for 목록 in 쇼핑리스트:
    print("항목{}({})".format(번호,목록))
    번호+=1
print ("-----------------------------------------------------------------------")
print("쇼핑 처음 항목은 {}입니다.".format(쇼핑리스트[0]))
구매완료항목 = 쇼핑리스트[0]
del 쇼핑리스트[0]
print("구매완료 항목은 {}입니다.".format(구매완료항목))
print("남은 구매목록은 {}개 입니다.".format(쇼핑리스트))

print ("-----------------------------------------------------------------------")
#Tuple
zoo = ("뱀", "코끼리", "팽귄")
print("Tuple 동물원 :{}, {}종류가 있어요".format(zoo, len(zoo)))

newzoo = "원숭이", "다람쥐", zoo
print("Tuple New 동물원 :{}, {}종류가 있어요".format(newzoo, (len(newzoo)-1)+len(newzoo[2])))

# zoo[0] #tuple은 고정값임으로 지울수 없습니다.
# print("Tuple 동물원 :{}, {}종류가 있어요".format(zoo, len(zoo)))
print ("-----------------------------------------------------------------------")
#Library
사전 ={"철수":"서울시",
"영희":"경기도",
"민영":"울산시",
"수민":"서울시",
"아영":"대구시",}
print("영희의 주소는", 사전["영희"])
print("지우기전 사전의 수는{}".format(len(사전)))
del 사전["수민"]
print("지우기후 사전의 수는{}".format(len(사전)))

for 이름, 주소 in 사전.items():
    print("이름({}), 주소({})".format(이름, 주소))
사전["혜은"] ="용인시"
for 이름, 주소 in 사전.items():
    print("이름({}), 주소({})".format(이름, 주소))
print ("-----------------------------------------------------------------------")
#enum
shoplist = ['apple', 'mango', 'carrot', 'banana']
name = 'swaroop'
# Indexing or 'Subscription' operation #
print('Item 0 is', shoplist[0])
print('Item 1 is', shoplist[1])
print('Item 2 is', shoplist[2])
print('Item 3 is', shoplist[3])
print('Item -1 is', shoplist[-1])
print('Item -2 is', shoplist[-2])
## Slicing on a list #
print('Item 1 to 3 is', shoplist[1:3])
print('Item 2 to end is', shoplist[2:])
print('Item 1 to -1 is', shoplist[1:-1])
print('Item start to end is', shoplist[:])
## Slicing on a string #
print('Character 0 is', name[0])
print('characters 1 to 3 is', name[1:3])
print("characters 2 to end is", name[2:])
print('characters 1 to -1 is', name[1:-1])
print('characters start to end is', name[:])

print ("-----------------------------------------------------------------------")
for i in shoplist[1:3]:
    print(i)
print ("-----------------------------------------------------------------------")
#집합(set)

남아메리카 = set(["브라질", "러시아", "인디아"])

if "브라질" in 남아메리카:
    print("브라질은 남아메리카에 있다")
북아메리카 = 남아메리카.copy()
print("변경({})".format(북아메리카))
북아메리카.add("캐나다")
print("변경({})".format(북아메리카))
북아메리카.issuperset(남아메리카)
print("변경({})".format(북아메리카))
#차집합(-), 교집합(&), 합집합(|)
#isdisjoint() - 두 집합이 공통 원소를 갖지 않는가?
#issubset() - 부분집합(subset)인가?
#issuperset() - 확대집합(superset)인가?
#union() - 합집합을 만들어 리턴
#update() - 합집합을 만들어 원본 데이터를 갱신(수정)
#difference() - 차집합을 만들어 리턴
#difference_update() - 차집합을 만들어 원본 데이터를 갱신
#(그냥 함수는 값을 리턴하는 반면 뒤에 update가 붙은 함수는 원본 데이터를 변경함)
#intersection() - 교집합을 만들어 리턴 
#intersection_update() - 교집합을 만들어 원본 데이터를 갱신
#symmetric_difference() - 대칭차를 만들어 리턴
#symmetric_difference_update() - 대칭차를 만들어 원본 데이터를 갱신
#대칭차란?
#둘 중 한 집합에는 속하지만 둘 모두에는 속하지는 않는 원소들의 집합이다.
print ("-----------------------------------------------------------------------")
#참조
나라이름 = ["브라질", "러시아", "인디아", "영국"]
참조자 = 나라이름
복사자 = 나라이름[:]
for i in 참조자:
    print(i)
print("원본 나라이름 지우기: ", 나라이름[0])
del 나라이름[0]

print("참조자의 변화는*************************")
for i in 참조자:
    print(i)
print("복사자의 변화는*************************")
for i in 복사자:
    print(i)
print ("======================================================================")
print("8) Class")

class Persion:
    #pass #None Action
    def __init__(self, name):
        self.name = name #self.name으로 self에 name인자가 생긴다.
    #return super().__init__(*args, **kwargs)#상위 호출

    def say_hi(self):#메소드기본 첫인자는 self를 통하여 자신을 넘겨준다.(C++의 this와같다)
        print("안녕하셔요~~~~~!({})".format(self.name))
print ("-----------------------------------------------------------------------")


#객체생성과 인스턴스 생성.
p=Persion("우석")#기본생성자 호출(내부에서 __init__()기본함수를 호출한다.
print(p)
p.say_hi()
dir(p)


print ("-----------------------------------------------------------------------")
class Robot:
    """Represents a robot, with a name."""
    # A class variable, counting the number of robots
    __population = 0 #private 맴버 변수
    population = 0 #일반 공개 멤버변수
    def __init__(self, name):
        """Initializes the data."""
        self.name = name
        print ("(Initializing {})".format(self.name))
 
        # When this person is created, the robot
        # adds to the population
        Robot.population += 1
 
    def die(self):
        """I am dying."""
        print ("{} is being destroyed!".format(self.name))
        Robot.population -= 1
 
        if Robot.population == 0:
            print ("{} was the last one.".format(self.name))
        else:
            print ("There are still {:d} robots working.".format(Robot.population))
 
    def say_hi(self):
        """Greeting by the robot. Yeah, they can do that."""
        print ("Greetings, my masters call me {} {}.".format(self.name,self.population))
    
    @classmethod #클래스 메소드로변환 하여 일종의 static 함수로 생성
    def how_many(cls):
        """Prints the current population."""
        print ("We have {:d} robots.".format(cls.population))

print ("-----------------------------------------------------------------------")

#Robot에 population를 갖고
#생성 객체들도 각각 population을 갖는다
#Robot의 population를 접근 할 때는 droid1.class.population로 접근 할 수 있다.
droid1 = Robot("R2-D2")
droid1.population = 10
droid1.say_hi()
Robot.how_many()
droid2 = Robot("C-3PO")
droid2.population = 30
droid2.say_hi()
Robot.how_many()
print ("\nRobots can do some work here.\n")
print ("Robots have finished their work. So let's destroy them.")
droid1.die()
droid2.die()

Robot.how_many()
print ("-----------------------------------------------------------------------")
class SchoolMember:
    '''Represents any school member.'''
    def __init__(self, name, age):
        self.name = name
        self.age = age
        print('(Initialized SchoolMember: {})'.format(self.name))
 
    def tell(self):
        '''Tell my details.'''
        print('Name:"{}" Age:"{}"'.format(self.name, self.age)),#줄바꿈 비활서 ,가 동작 하지 않는다.

class Teacher(SchoolMember): #SchoolMember를 상속함을 표시 한다.
    '''Represents a teacher.'''
    def __init__(self, name, age, salary):
        SchoolMember.__init__(self, name, age)#파이썬은 기본 클래스의 생성자를 자동으로 호출해 주지 않으므로 명시적으로 이것을 호출해
        self.salary = salary
        print ('(Initialized Teacher: {})'.format(self.name))
 
    def tell(self):
        SchoolMember.tell(self)#부모클래스 명시적 호출
        print ('Salary: "{:d}"'.format(self.salary))

class Student(SchoolMember): #SchoolMember를 상속함을 표시 한다.
    '''Represents a student.'''
    def __init__(self, name, age, marks):
        SchoolMember.__init__(self, name, age)#부모클래스 __init__() 명시적 호출
        self.marks = marks
        print('(Initialized Student: {})'.format(self.name))
 
    def tell(self):
        SchoolMember.tell(self)#부모클래스 명시적 호출
        print ('Marks: "{:d}"'.format(self.marks))
print ("-----------------------------------------------------------------------")

t = Teacher('Mrs. Shrividya', 40, 30000)
s = Student('Swaroop', 25, 75)

members = [t, s]
for member in members:
    # Works for both Teachers and Students
    member.tell()


print ("======================================================================")
#프로그래밍
def 문자열_뒤집기(문자열):
    return 문자열[::-1]#문자열을 뒤집어서 출력 한다.
def 이것은_앞뒤가_같은문자열입니다(문자열):
    return 문자열 == 문자열_뒤집기(문자열)

사용장입력 = "madam" #input("신규단어를 입력하세요: ")
print("입력문자:{}".format(사용장입력))
if 이것은_앞뒤가_같은문자열입니다(사용장입력):
    print("앞뒤가 같은 문자열입니다.")
else:
    print("앞뒤가 같지않은 문자열입니다.")

print ("======================================================================")
#파일입출력
시재 = '''\
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!
'''

#읽기 모드 ( 'r' ), 쓰기 모드 ( 'w' ), 덧붙임 모드( 'a' )
#텍스트 모드 ( 't' ), 바이너리 모드 ( 'b' )
파일 = open("시재.txt", "w")
파일.write(시재)
파일.close()


파일 = open("시재.txt", "r")
nCount =1
while True:
    한줄읽기 = 파일.readline()
    if len(한줄읽기) == 0:
        break#읽은 라인의 길이가 0라면
    print("{0}:{1}".format(nCount ,한줄읽기), end='')
    nCount+=1
파일.close()

print ("======================================================================")
#pickel =>어떤 객체든지 파일로 저장 가능.
import pickle
저장파일명 ="쇼핑리스트.dat"
쇼핑리스트 =["사과", "망고", "배", "감"]
f = open(저장파일명, "wb")#쓰기 바이너리 형태
pickle.dump(쇼핑리스트, f)#Object를 File에 Dump하여 저장
f.close()

del 쇼핑리스트

f = open(저장파일명, "rb")#읽기 바이너리 형태
쇼핑리스트 = pickle.load(f)#File로부터 바이너리 Data를 읽는다.
f.close()
쇼핑리스트.sort()
print(쇼핑리스트)

print ("======================================================================")
#유니코드
#encoding=utf-8
import io
f = io.open("abc.txt", "wt", encoding="utf-8")
f.write(u"Imagine non-English language here")
f.close()
f = io.open("abc.txt", encoding="utf-8")
print (f.read())
f.close()

print ("======================================================================")
#예외처리
try:
    #text = raw_input('Enter something --> ')
    text = input('Enter something --> ')
except EOFError:
    print ('Why did you do an EOF on me?')
except KeyboardInterrupt:
    print ('You cancelled the operation.')
else:
    print ('You entered {}'.format(text))
print ("======================================================================")
#예외 발생
class ShortInputException(Exception):
    '''A user-defined exception class.'''
    def __init__(self, length, atleast):
        Exception.__init__(self)
        self.length = length
        self.atleast = atleast

try:
    text = input('Enter something --> ')
    if len(text) < 3:
        raise ShortInputException(len(text), 3)
except EOFError:
    print ('Why did you do an EOF on me?')
except ShortInputException as ex:
    print (('ShortInputException: The input was ' + \
    '{0} long, expected at least {1}')\
    .format(ex.length, ex.atleast))
else:
    print ('No exception was raised.')

print ("======================================================================")
#try Finally
import sys
import time
f = None
try:
    f = open("시재.txt", "r")
    while True:
        line = f.readline()
        if len(line) == 0:
            break
        print (line, end='')
        sys.stdout.flush()
        print ("Press ctrl+c now")
        time.sleep(2)
except IOError:
    print ("Could not find file poem.txt")
except KeyboardInterrupt:
    print ("!! You cancelled the reading from the file.")
finally:
    if f:
        f.close()
    print ("(Cleaning up: Closed the file)")


#finally의 close()를 with를 통해 완료시 자동 수행한다.
with open("poem.txt") as f:
    for line in f:
        print (line, end="")

byte_of_python.pdf
2.87MB

'작업 > Python' 카테고리의 다른 글

Python byte Data 읽기/쓰기  (0) 2021.08.20
Python "exe" 실행 파일 만들기  (3) 2021.07.22
Visual Studio Python & Tensorflow 설치  (4) 2021.07.12

1) 설치 링크

https://visualstudio.microsoft.com/ko/thank-you-for-downloading-visual-studio-for-python/?sku=Community&rel=16&rid=30001# 

 

Python용 Visual Studio를 다운로드해 주셔서 감사합니다. - Visual Studio

 

visualstudio.microsoft.com

2) 설치 진행

3) 새 프로젝트 구성

4) tensorflow 설치

- import tenso~시 링크에 뜨지 않는다면

- 패키지 관리 클릭 "pip install --upgrade tensorflow" 입력 후 엔터==> 설치 시작

 

5) 실행과 결과 출력

'작업 > Python' 카테고리의 다른 글

Python byte Data 읽기/쓰기  (0) 2021.08.20
Python "exe" 실행 파일 만들기  (3) 2021.07.22
Python - 기본 문법 예제 (1)  (0) 2021.07.20

+ Recent posts