Python - Sizuha/devdog GitHub Wiki

์„ค์ •

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'
โš ๏ธ **GitHub.com Fallback** โš ๏ธ