Skip to content
Sizuha edited this page Sep 11, 2024 · 3 revisions

설정

MySQL 라이브러 설치시 오류

https://stackoverflow.com/questions/76585758/mysqlclient-cannot-install-via-pip-cannot-find-pkg-config-name-in-ubuntu

$ pip3 install mysqlclient

Collecting mysqlclient
  Using cached mysqlclient-2.2.0.tar.gz (89 kB)
  Installing build dependencies ... done
  Getting requirements to build wheel ... error
  error: subprocess-exited-with-error

  × Getting requirements to build wheel did not run successfully.
  │ exit code: 1
  ╰─> [25 lines of output]
      Trying pkg-config --exists mysqlclient
      Command 'pkg-config --exists mysqlclient' returned non-zero exit status 1.
      Trying pkg-config --exists mariadb
      Command 'pkg-config --exists mariadb' returned non-zero exit status 1.
      Traceback (most recent call last):
        File "/usr/lib/python3/dist-packages/pip/_vendor/pep517/in_process/_in_process.py", line 363, in <module>
          main()
        File "/usr/lib/python3/dist-packages/pip/_vendor/pep517/in_process/_in_process.py", line 345, in main
          json_out['return_val'] = hook(**hook_input['kwargs'])
        File "/usr/lib/python3/dist-packages/pip/_vendor/pep517/in_process/_in_process.py", line 130, in get_requires_for_build_wheel
          return hook(config_settings)
        File "/usr/lib/python3/dist-packages/setuptools/build_meta.py", line 162, in get_requires_for_build_wheel
          return self._get_build_requires(
        File "/usr/lib/python3/dist-packages/setuptools/build_meta.py", line 143, in _get_build_requires
          self.run_setup()
        File "/usr/lib/python3/dist-packages/setuptools/build_meta.py", line 158, in run_setup
          exec(compile(code, __file__, 'exec'), locals())
        File "setup.py", line 154, in <module>
          ext_options = get_config_posix(get_options())
        File "setup.py", line 48, in get_config_posix
          pkg_name = find_package_name()
        File "setup.py", line 27, in find_package_name
          raise Exception(
      Exception: Can not find valid pkg-config name.
      Specify MYSQLCLIENT_CFLAGS and MYSQLCLIENT_LDFLAGS env vars manually
      [end of output]

해결법

$ sudo apt-get install python3-dev default-libmysqlclient-dev build-essential

실행 후, 다시 설치 시도.

확인

설치된 Python 경로 확인

>>> import sys
>>> print sys.prefix

문법

Python 문법 참조

날짜/시간

date, time, datetime 객체 사용.

날짜 시간 포맷팅

time.strftime()

C함수를 쓰기 때문에 유니코드를 전달할 때는 포맷팅 문자열을 utf-8로 인코딩을 해야함.

time.strftime(u'%d\u200f/%m\u200f/%Y %H:%M:%S'.encode('utf-8'), t).decode('utf-8')

현재 날짜/시간

from datetime import datetime

datetime.today()
datetime.now([tz])

요일 확인

 datetimeObj.weekday()

Return the day of the week as an integer, where Monday is 0 and Sunday is 6. The same as self.date().weekday().

datetimeObj.isoweekday()

Return the day of the week as an integer, where Monday is 1 and Sunday is 7. The same as self.date().isoweekday().

Sleep

import time
time.sleep(sec)

CSV

Read

import csv

with open('some.csv', 'rb') as f:
    reader = csv.reader(f)
    for row in reader:
        print row

Write

import csv

with open('filename.csv', 'w') as f:
    writer = csv.writer(f, lineterminator='\n')
    writer.writerow(list)
    writer.writerows(array2d)

JSON

http://docs.python.org/2/library/json.html

JSON Encoding

import json

json.dumps(data)
json.dumps(data, sort_keys=True)

JSON Decoding

import json

data = json.loads(json_string)

Http, URL

GET

import urllib

url = 'http://dna.daum.net'
data = urllib.urlopen(url).read()
import urllib2
try:
  data = urllib2.urlopen(url).read()
except urllib2.HTTPError, e:
  print "HTTP error: %d" % e.code
except urllib2.URLError, e:
  print "Network error: %s" % e.reason.args[1]

인증이 필요한 경우

import urllib2

url = 'http://www.abc.com/index.html'
username = 'user'
password = 'pass'
p = urllib2.HTTPPasswordMgrWithDefaultRealm()

p.add_password(None, url, username, password)

handler = urllib2.HTTPBasicAuthHandler(p)
opener = urllib2.build_opener(handler)
urllib2.install_opener(opener)

page = urllib2.urlopen(url).read()

POST

import urllib

url = "http://apis.daum.net/search/knowledge?&;output=xml&q=OpenAPI"

apikey = "DAUM_SEARCH_DEMO_APIKEY"
output = "xml"
q = "OpenAPI"

params = urllib.urlencode({
  'apikey': apikey,
  'output': output,
  'q': q
})

data = urllib.urlopen(url, params).read()

OS

명령행 인수

import sys

argc = len(sys.argv)

print 'argument 1: ' + sys.argv[1]
print 'argument 2: ' + sys.argv[2]
# . . .

현재 파일의 경로 가져오기

import os.path

os.path.dirname(__file__)

Command 실행

import subprocess
subprocess.call("command1")
subprocess.call(["command1", "arg1", "arg2"])

IO

File IO

f = open("file.name", "r", encoding="utf-8")
s = f.read()
f.close()

파일 존재여부 확인

import os.path
os.path.exists(path)

파일 및 디렉토리 목록

for root, dirs, files in os.walk(directory):
    for file in files:
        if file.endswith('.txt'):
            print file

파일 이름만 가져오기

>>> print os.path.splitext(os.path.basename("hemanth.txt"))[0]
hemanth

Random

>>> import random
>>> random.random()
0.90389642027948769

>>> random.randrange(1,7)
6

>>> abc = ['a', 'b', 'c', 'd', 'e']
>>> random.shuffle(abc)
>>> abc
['a', 'd', 'e', 'b', 'c']

>>> abc
['e', 'd', 'a', 'c', 'b']
>>> random.choice(abc)
'a'
Clone this wiki locally