반응형

파이썬 3의 특징

  1. 모든 문자열은 유니코드로 처리한다.
  2. 변수명에 한글을 사용할 수도 있다.
  3. print문은 없어지고 함수 print()만 사용할 수 있다.
  4. raw_input()은 없어지고 input()을 사용한다.

 

 

 

반응형
반응형
python으로 android phone에 웹서버 만들기

 

Tutorial : http://code.google.com/p/android-scripting/wiki/Tutorials

 

 

httpd.py

import SimpleHTTPServer
from os import chdir

 

chdir('/sdcard/')

 

SimpleHTTPServer.test()

 

실행하면 아래처럼 로그가 올라온다.

그럼, 폰의 웹브라우저로 접속하면 아래와 같다.

 

 무선 AP에 접속 중이면 같은 망에 있는 다른 디바이스에서도 접근이 가능하도록 고유 IP를 찾아서 보자.

shell로 접속해서 netcfg를 실행하면  "eth0"가 실행중인 것이 지금 실행중인 Lan정보이다.

그 IP를 사용하면 된다.

 

 

 

반응형
반응형

파이썬을 이용한 단어모음파일에서  무작위로 단어 프린트하기

wordlist.txt : 단어모음 text 파일

wordlist.py : 단어장 스크립트 파일

 

Line.3 : getcwd()를 이용하여 알아낸 경로에 'sl4a'가 포함되어 있으면 경로를 지정해 주도록한다.

Line.4 : 파일을 읽는다.

Line.5 : 파일내용을 splitlines(위 이미지는 오타)로 한줄씩 분할한다.

            lambda 함수는 간단한 함수를 한줄로 줄여준다.

Line.8 : 사용자의 입력을 무한반복으로 기다린다.

 

 

 

 

 

 

반응형
반응형

예제 스크립트가 많아지면 파일및 폴더관리가 쉽지 않다.

+ADD 버튼 선택하여 Folder를 생성해서 Shell로 관리하면 된다.

물론 PC와 USB 연결해서 정리하면 훨씬 빠르겠다.

간단 명령어

pwd : 현재 위치를 보여준다.

cd scripts : scripts 폴더로 이동한다.

ls : 디렉토리내의 파일목록을 보여준다.

ls -l 또는 ll : 자세리 파일목록을 보여준다.

mv hello_android.py  scripts : scripts 폴더로 hello_android.py 파일을 이동시킨다.

rm hello_android.py: 파일 삭제

 

사진찍기, 연속 촬영하기

 

import android,time

 

a = android.Android()

 

def pic():

    return 'sdcard/sl4a/scripts/img/'\

         + time.strftime('%Y%m%d%H%M%S')\

         + '.jpg'

 

def say(it):

    a.ttsSpeak(it)

    a.makeToast(it)

 

food = 'Keeeemcheeeee!'

 

for i in range(3):

    for j in range(3,0,-1):

        say(str(j))

        time.sleep(3)

    say(food)

    a.cameraCapturePicture(pic())

 

 

 

 

 

 

 

* sleep 을 위해 time을 import 한다.

* 순차적 파일명 생성을 위해서 time.strftime을 사용한 파일명 구현

 

 

반응형
반응형

안드로이드폰에서 파이썬을 사용하려면 SL4A(Scripting Layer for Android),

 Python for Android를 설치해야 한다.

 

SL4A 설치 : http://code.google.com/p/android-scripting/


QR로 다운 받을 수 있다. : http://android-scripting.googlecode.com/files/sl4a_r6.apk

 

SL4A를 실행하고 Menu > View > Interpreters 를 선택하면 "SHELL"이라는 메뉴가 나타난다.

shell 을 통해서 안드로이드폰과 대화를 할 수 있다.

 

난 "SHELL"이 나오지 않아서 바로 Python for Android를 설치해버렸다.

 

Python for Android 설치 : http://code.google.com/p/android-scripting/downloads/detail?name=PythonForAndroid_r4.apk

File:
Description:
Latest Python release.

Note that Python for Android is now being hosted here:
http://code.google.com/p/python-for-android/

This is a copy of the lastest release, placed here for convenience.
SHA1 Checksum: ff4dfef760880fd1cdbc164045cc859947ecbe1d What's this?

 

설치하면 Install 메뉴가 나오는데, 바로 Install 터치.

몇 번의 다운로드와 설치가 끝나고, Install > UnInstall 로 변경된다.

 

그럼, 다시 SL4A를 실행하면  Script와 Shell이 대기중일 것이다.

스크립트 목록이 나오는데, shell화면으로 가고 싶으면 View > Interpreters 로 이동한다.

 

Interpreters에서 python을 선택하면 파이썬 shell로 들어간다. 안드로이드를 import해서 핸드폰 기능을 테스트 해 볼 수 있다.

 

안드로이드 모듈을 가져온다.

>>>import android

>>>droid = android.Android()

 

>>>droid.vibrate()

: 진동을 실행한다. 그런데, 한번밖에 되지 않는다.

 

>>>droid.ttsSpeak('anneung')

: '안녕'이라고 스피커에서 나온다.

 

>>>def ann(): droid.ttsSpeak('anneung')

>>>ann()

>>>ann()

 

 

 

 

 

 

 

 

 

 

스크립트 파일을 추가해서 파일을 실행 해 볼 수 있다.

파일을 생성하고, MENU > Save & Run을 선택하면 저장하면서 실행이 된다.

반응형
반응형

기본 예제 - "예제중심의 파이썬" 1장

 

source

 

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

teamstandings = [('SK', 38,25,0),
                 ('SS',39,27,2),
                 ('KIA',38,29,0),
                 ('LG',36,30,0),
                 ('HH',29,39,1)
                 ]

for ts in teamstandings:
    team, win, lost, draw = ts
    games = win + lost + draw
    winrate = float(win) / (win + lost)
    format = '%s 팀은 총  %d 경기 중  %d 승으로 승률은   %.3f 입니다. '
    print(format % (team, games, win, winrate))
    #print( team, games, win, winrate )

# 4.1 숫자 계산
print("=" * 20 + '  4.1. 숫자계산    ' + "=" * 20)

print("1 + 2 = " , (1+2))
print("50 - 4 =" , 50-4)
print("5000 / 3 = ", 5000/3)
print("5000.0 / 3.0 = ", 5000.0/3.0)

print()
print('-' * 10 , 'calendar', '-' * 10)
import calendar
calendar.prmonth(2018, 2)

print()
print('-' * 10 , '문자열', '-' * 10)

print(' show * 3 = ', 'show' * 3)
print(' 11,200,000.replace(\',\', \'\' ) = ', '11,200,000'.replace(',', ''))
# 앞쪽 여섯글자
print('0~6 :  \'follower\'[0:6] = ', 'follower'[0:6])
# 앞의 0은 생략 가능
print('0~6 :  \'follower\'[:6] = ', 'follower'[:6])
# 4번부터 끝까지
print('4~end :  \'followerwhite\'[4:] = ', 'followerwhite'[4:])
#뒤에서 네번째부터 끝까지
print('-4 :  \'followerwhite\'[-4:] = ', 'followerwhite'[-4:])
# 단어의 첫 글자는 대문자, 나머지는 소문자
print(' \'espresso\'.title() = ', 'espresso'.title())
# 문자열의 길이(공백, 기호도 포함된다.)
print(' len(\'what are you?\') = ', len('what are you?'))
# 문장에서 특정문자열이 몇 번 나오는지 count
ans = "We're  here because you are looking for the best of the best of the best, sir!"
print(ans)
print( " ans.count(\'best\') = ",ans.count('best') )

 

print()
print('-' * 10 , ' 날짜 계산 ', '-' * 10)
from datetime import date

t   = date.today()
print( ' today : ' , t )
c   = date(2013, 9, 19)
gap = abs(c - t).days
subscrib = " %s - %s = - %s days. remain."
print( subscrib % (c, t, gap) )

print()
print('-' * 10 , ' 로또 번호 뽑기', '-' * 10)

lotto = list(range(1,46))
print(lotto)
import random
# lotto를 무작위로 섞는다.
random.shuffle(lotto)
print(lotto)
# 하나의 숫자를 꺼낸다.
print(' 1.  ', lotto.pop())
print(lotto)
# 하나의 숫자를 꺼낸다.
print(' 2.  ', lotto.pop())

for i in range(5):
    print(' ',i + 1,'. ', lotto.pop())
print(lotto)


family = ['father','mother','I','sister']
i = 0
print('family = ' , family )
for x in family:
    i += 1
    print(i ,'  - ', x)

print(range(4,8))   
for i in range(4,8): print('  - ', i)   

 

print('카이사르 암호문 만들기' , '-' * 20);
# from string import maketrans
# tt = maketrans('abcdefghijklmnopqrstuvwxyz', 'DEFGHIJKLMNOPQRSTUVWXYZABC')


print('  While 문   ' , '-' * 20);
num = 1
while num <= 10:
    print( num )
    num += 1

print('  IF 문   ' , '-' * 20);
a = 1234 * 4
b = 13456/4
if a < b:
    print( a )
else:
    print( b )
   
c = 15 * 5
d = 15 + 15 + 15 + 15 + 15

if c > d :
    print(' c > d ')
elif c == d:
    print(' c == d ')
else:
    print(' C < d ')
   
print('  구구단   ' , '-' * 20);
left = 8
rightlist = range(1,10)
for right in rightlist:
    print(' %d * %d = %d' % (left, right, left * right))

# * 로 마름모 만들기
a = 1
b = 10
c = 0
d = 10
for i in range(10):
    if a == 1:
        print(' ' * b + ('*' * a))
    else:
        print(' ' * b + ('*' * a) + ('*' * c) )
    a += 1
    c += 1
    b -= 1
print('*'*a + '*'*c)
for i in range(10):
    c -= 1
    a -= 1
    print(' ' * b, '*' * a + ('*' * c) )
    b += 1


 

 

 

result 

 SK 팀은 총  63 경기 중  38 승으로 승률은   0.603 입니다.
SS 팀은 총  68 경기 중  39 승으로 승률은   0.591 입니다.
KIA 팀은 총  67 경기 중  38 승으로 승률은   0.567 입니다.
LG 팀은 총  66 경기 중  36 승으로 승률은   0.545 입니다.
HH 팀은 총  69 경기 중  29 승으로 승률은   0.426 입니다.
====================  4.1. 숫자계산    ====================
1 + 2 =  3
50 - 4 = 46
5000 / 3 =  1666.6666666666667
5000.0 / 3.0 =  1666.6666666666667

---------- calendar ----------
   February 2018
Mo Tu We Th Fr Sa Su
          1  2  3  4
 5  6  7  8  9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28
 
---------- 문자열 ----------
 show * 3 =  showshowshow
 11,200,000.replace(',', '' ) =  11200000
0~6 :  'follower'[0:6] =  follow
0~6 :  'follower'[:6] =  follow
4~end :  'followerwhite'[4:] =  owerwhite
-4 :  'followerwhite'[-4:] =  hite
 'espresso'.title() =  Espresso
 len('what are you?') =  13
We're  here because you are looking for the best of the best of the best, sir!
 ans.count('best') =  3

----------  날짜 계산  ----------
 today :  2013-02-08
 2013-09-19 - 2013-02-08 = - 223 days. remain.

----------  로또 번호 뽑기 ----------
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45]
[21, 40, 1, 8, 15, 9, 11, 23, 31, 20, 10, 28, 13, 41, 19, 6, 12, 39, 43, 18, 27, 16, 24, 5, 29, 14, 30, 34, 35, 38, 32, 3, 17, 45, 7, 37, 4, 2, 25, 22, 33, 42, 44, 26, 36]
 1.   36
[21, 40, 1, 8, 15, 9, 11, 23, 31, 20, 10, 28, 13, 41, 19, 6, 12, 39, 43, 18, 27, 16, 24, 5, 29, 14, 30, 34, 35, 38, 32, 3, 17, 45, 7, 37, 4, 2, 25, 22, 33, 42, 44, 26]
 2.   26
  1 .  44
  2 .  42
  3 .  33
  4 .  22
  5 .  25
[21, 40, 1, 8, 15, 9, 11, 23, 31, 20, 10, 28, 13, 41, 19, 6, 12, 39, 43, 18, 27, 16, 24, 5, 29, 14, 30, 34, 35, 38, 32, 3, 17, 45, 7, 37, 4, 2]
family =  ['father', 'mother', 'I', 'sister']
1   -  father
2   -  mother
3   -  I
4   -  sister
range(4, 8)
  -  4
  -  5
  -  6
  -  7
카이사르 암호문 만들기 --------------------
  While 문    --------------------
1
2
3
4
5
6
7
8
9
10
  IF 문    --------------------
3364.0
 c == d
  구구단    --------------------
 8 * 1 = 8
 8 * 2 = 16
 8 * 3 = 24
 8 * 4 = 32
 8 * 5 = 40
 8 * 6 = 48
 8 * 7 = 56
 8 * 8 = 64
 8 * 9 = 72
          *
         ***
        *****
       *******
      *********
     ***********
    *************
   ***************
  *****************
 *******************
*********************
 *******************
  *****************
   ***************
    *************
     ***********
      *********
       *******
        *****
         ***
          *
done.

 

반응형
반응형

 웹 파이썬 shell - http://shell.appspot.com/

 

설치 필요없이 인터넷에 연결되어 있으면 당장 파이썬을 사용해 볼 수 있는 방법.

 

반응형
반응형

일단 aptana 다운받아서 설치하고.

Preferences 들어가서 PyDev 항목 선택해서 "Python Interpreters"에 설치된 python 실행파일을 연결해주면 된다.

 

그리고, "PyDev perspective"를 선택해서 python 구문을 작성한 다음 실행버튼 에서 "Run As " > "Python Run" 을 선택한다. 그러면, Console에 결과가 나온다.  

반응형

+ Recent posts