python expected an indented block error

 

파이썬 코드 작성 시 흔히 보이는 에러이다.

 

에러 line 34를 보면 if문인데 들여쓰기가 없다.

 

python if문을 쓸때에는 다음과 같이 들여쓰기로 코드를 구분해야한다.

# Python
if 조건문1:
	명령문1
elif 조건문2:
	명령문2
else:
	명령문3

** IndentationError: expected an indented block 에러는 들여쓰기를 잘해주면 해결이 된다.

 

 

'개발일지 > Python' 카테고리의 다른 글

[Python] 문자열에서 특정 문자 찾기  (0) 2020.08.04
python 버전 upgrade  (0) 2020.05.27
[Python] 리스트 초기화  (0) 2020.05.25
[Python] 소켓통신 (server, client)  (0) 2020.05.22
[Python] 파이썬 백그라운드 실행  (0) 2020.04.29

1. in

host = "chichi-story.tistory.com"
search = "story"
if search in host:
  print("Okay")
else:
  print("None")

 

위 예제에서는 변수 host에서 해당 문자 search가 존재하는지 확인한 후 해당하는 메시지를 출력합니다.

실제 동일한 텍스트가 존재하므로 "Okay"가 출력될 것입니다.

 

2. find()

find()를 사용하면 존재 여부에 따라 해당하는 위치값 반환

str = "abcdefghijklmn"
search = "e"

indexNo = str.find(search)
print indexNo


# 결과값 : 4

이제 위의 코드의 실행하면 다음과 같이 해당하는 위치값을 나타나게됩니다. 시작점부터 0을 기준으로 합니다.

값이 존재하지 않으면 "-1"을 반환

str = "abcdef"
search = "t"

result = str.find(search)

if result == -1:
  print "None"

 

python version upgrade

2.7에서 3.5로 버전 UP

- 현재 python 버전 확인

$ python –V 
Python 2.7.12

 

 

- python  위치 확인

$ which python 
/usr/bin/python

 

- 어떤 파일을 가리키는지 확인

$ ls –al /usr/bin/python 
lrwxrwxrwx 1 root root 9 4월 14 14:40 /usr/bin/python -> python2.7

 

- python 실행 파일 목록 확인

$ ls /usr/bin/ | grep python 
dh_python2
dh_python3
python
python-config
python2
python2-config
python2-pbr
python2.7
python2.7-config
python3
python3.5
python3.5m
python3m
x86_64-linux-gnu-python-config
x86_64-linux-gnu-python2.7-config

 

- python 옵션 변경

$ sudo update-alternatives —config python
update-alternatives: 오류: no alternatives for python //--등록된 버전이 없음을 의미

 

- 실행파일을 등록

 

$ sudo update-alternatives --install /usr/bin/python python /usr/bin/python2.7 1
update-alternatives: using /usr/bin/python2.7 to provide /usr/bin/python (python) in auto mode
$ sudo update-alternatives --install /usr/bin/python python /usr/bin/python3.5 2
update-alternatives: using /usr/bin/python3.5 to provide /usr/bin/python (python) in auto mode

$ sudo update-alternatives --config python
대체 항목 python에 대해 (/usr/bin/python 제공) 2개 선택이 있습니다.


선택 경로 우선순위 상태

------------------------------------------------------------

* 0 /usr/bin/python3.5 2 자동 모드

1 /usr/bin/python2.7 1 수동 모드

2 /usr/bin/python3.5 2 수동 모드


Press <enter> to keep the current choice[*], or type selection number: 2

 

 

- 변경 완료된 python 버전 확인

$ python -V
Python 3.5.2

python list 초기화

1. list data만 삭제 (list를 비어있는채로 만들때)

list = [1,2,3,4,5]
del list[:]

2. list 자체를 메모리에서 삭제

del list

'개발일지 > Python' 카테고리의 다른 글

[Python] 문자열에서 특정 문자 찾기  (0) 2020.08.04
python 버전 upgrade  (0) 2020.05.27
[Python] 소켓통신 (server, client)  (0) 2020.05.22
[Python] 파이썬 백그라운드 실행  (0) 2020.04.29
[Python] MQTT 사용  (0) 2020.04.07

python 소켓통신

1. socket-server.py

#-*- coding:utf-8 -*-

import socket

# 통신 정보 설정
IP = ''
PORT = 5050
SIZE = 1024
ADDR = (IP, PORT)

# 서버 소켓 설정
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server_socket:
    server_socket.bind(ADDR)  # 주소 바인딩
    server_socket.listen()  # 클라이언트의 요청을 받을 준비

    # 무한루프 진입
    while True:
        client_socket, client_addr = server_socket.accept()  # 수신대기, 접속한 클라이언트 정보 (소켓, 주소) 반환
        msg = client_socket.recv(SIZE)  # 클라이언트가 보낸 메시지 반환
        print("[{}] message : {}".format(client_addr,msg))  # 클라이언트가 보낸 메시지 출력

        client_socket.sendall("welcome!".encode())  # 클라이언트에게 응답

        client_socket.close()  # 클라이언트 소켓 종료

 

2. socket-client.py

#-*- coding:utf-8 -*-

import socket

# 접속 정보 설정
SERVER_IP = '127.0.0.1'
SERVER_PORT = 5050
SIZE = 1024
SERVER_ADDR = (SERVER_IP, SERVER_PORT)

# 클라이언트 소켓 설정
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as client_socket:
    client_socket.connect(SERVER_ADDR)  # 서버에 접속
    client_socket.send('hi'.encode())  # 서버에 메시지 전송
    msg = client_socket.recv(SIZE)  # 서버로부터 응답받은 메시지 반환
    print("resp from server : {}".format(msg))  # 서버로부터 응답받은 메시지 출력

 

3. 결과 

- server (무한루프로 대기)

- client

'개발일지 > Python' 카테고리의 다른 글

[Python] 문자열에서 특정 문자 찾기  (0) 2020.08.04
python 버전 upgrade  (0) 2020.05.27
[Python] 리스트 초기화  (0) 2020.05.25
[Python] 파이썬 백그라운드 실행  (0) 2020.04.29
[Python] MQTT 사용  (0) 2020.04.07

python 백그라운드 실행

$ nohup python test.py &

  • 기본 출력은 실행파일과 같은 위치에 nohup.out 이라는 파일에 저장

$ nohup python test.py > print.log &

  • 출력 파일 변경은 일반적인 redirect 옵션을 사용
  • 출력 파일 내용이 실시간으로 생기지 않고 어느정도 내용이 쌓이면 저장

$ nohup python -u test.py > print.log &

  • -u 옵션 사용해서 바로 확인이 가능

$ nohup python test.py 1>/dev/null 2>&1  &

  • 로그 안남기기

'개발일지 > Python' 카테고리의 다른 글

[Python] 문자열에서 특정 문자 찾기  (0) 2020.08.04
python 버전 upgrade  (0) 2020.05.27
[Python] 리스트 초기화  (0) 2020.05.25
[Python] 소켓통신 (server, client)  (0) 2020.05.22
[Python] MQTT 사용  (0) 2020.04.07

 

1. mqtt 설치

pip install paho-mqtt

2. python (subscribe.py)

import paho.mqtt.client as mqtt

# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))
    client.username_pw_set("user", "1234") # broker에 password가 설정되어 있다면 추가 없으면 생략
    client.subscribe("#") # Topic

# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
    msg.payload = msg.payload.decode("utf-8")
    print("topic: "+msg.topic+" value: "+msg.payload)



client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message

client.connect("localhost") # broker IP

client.loop_forever() #무한루프

 

 

'개발일지 > Python' 카테고리의 다른 글

[Python] 문자열에서 특정 문자 찾기  (0) 2020.08.04
python 버전 upgrade  (0) 2020.05.27
[Python] 리스트 초기화  (0) 2020.05.25
[Python] 소켓통신 (server, client)  (0) 2020.05.22
[Python] 파이썬 백그라운드 실행  (0) 2020.04.29

+ Recent posts