python memorandum

standard

End

sys.exit()  #Throws a system exit exception
sys.exit('error!') #Spits an abend string to stderr and throws a status 1 SystemExit exception
os._exit(n) #End process with status n Do not throw an exception
raise exception #Throw an exception

path

#Script runtime path
__file__    #Relative path of the script file itself
os.getcwd() #Absolute path of the current directory
sys._getframe().f_code.co_name  #Function name being executed/Method name
os.path.dirname(os.path.abspath(__file__)) #Absolute path to the script's parent directory (because I use it often)
#See path
os.path.dirname(filepath)  #File path → Directory path one level higher
os.path.basename(filepath) #File path → File name
os.path.abspath(filepath)  #File relative path → File absolute path
os.path.exists(filepath)   #File existence check → True or False
os.path.isfile(filepath)   #Check if it is a file → True or False
os.path.isdir(dirpath)     #Check if it is a directory → True or False
os.wark(dirpath)           #The result of tracing under the command like the find command of Linux is[(path, [dir,...], [file,...]),...]Form of
#File operations
os.mkdir(dirname)          #Directory creation
os.makedirs(dirpath)       #Directory creation(mkdir -Same as p)
shutil.copyfile(src, dst)  #File → Copy File
shutil.copy(src, dst)      #File → Copy Directory
shutil.copytree(src, dst)  #Directory → Copy Directory
os.remove(filepath)        #File deletion
os.rmdir(dirpath)          #Delete empty directory
os.removedirs(dirpath)     #Delete directory tree (error if there is a file)
shutil.rmtree(dirpath)     #Delete directory tree (delete files even if they exist)

File read / write

#New notation (automatically close)
with open(filename, 'w') as file:
    file.write(str)
#Old notation
file = open(filename, 'w')
try:
    file.write(str)
finally:
    file.close()
#Character code specification
with codecs.open(filename, 'w', 'shift_jis') as file:
    file.write(str)

conf file operation

[section]
option = value

↑ is ↓

config['section']['option'] = 'value'

It basically operates according to the dictionary type, but the following are different.

Rebuild it as a dictionary type with {key: {k: v for k, v in value.items ()} for key, value in config.items ()}.

import configparser
config = configparser.ConfigParser()
config['DEFAULT'] = {'ServerAliveInterval': '45',  #Set item in DEFAULT section
                     'Compression': 'yes',
                     'CompressionLevel': '9'}
with open('example.ini', 'w') as configfile:
    config.write(configfile)
#reading
config = configparser.ConfigParser()
config.read([os.path.dirname(__file__) + '/' + INI_FILE], encoding='utf-8')
userid = config['DEFAULT']['userid']

SQLite3

#Ready to use
import sqlite3
conn = sqlite3.connect('example.sqlite3')
c = conn.cursor()
#SQL issuance
c.execute("""INSERT INTO stocks
          VALUES ('2006-01-05','BUY','RHAT',100,35.14);""")
##Embed variables in strings Use tuples for embedding
t = ('RHAT',)
c.execute('SELECT * FROM stocks WHERE symbol=?', t)
##Embed multiple tuples
purchases = [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
             ('2006-04-05', 'BUY', 'MSFT', 1000, 72.00),
             ('2006-04-06', 'SELL', 'IBM', 500, 53.00),
            ]
c.executemany('INSERT INTO stocks VALUES (?,?,?,?,?)', purchases)
#4 SELECT result reference methods
for row in c.execute('SELECT * FROM table'): #Take out as an iterator
    print(row)
row = c.fetchone() #Extract one line Returns None if there is no line to extract
some_rows = fetchmany(size=cursor.arraysize) #Extract the specified number of lines
all_rows = fetchall() #Extract all lines

Bonus:

#Table existence check
SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name=table;
#Create table
CREATE TABLE table(column1 [datatype1] [,column2 [datatype2] ...]);
#Add data
INSERT INTO t (columname1,column2…) VALUES (value1,value2…);
#Data update
UPDATE table SET column::=value [,...] [WHERE conditions];
#Search
SELECT column [,...] FROM table [WHERE conditions];
#Delete table
DROP TABLE table;

phantomJS with selenium

from selenium import webdriver
driver = webdriver.PhantomJS() #PhantomJS driver creation
driver = webdriver.PhantomJS(service_log_path=log_name) #Log file specification(default: './ghostdriver.log')
driver = webdriver.PhantomJS(service_log_path=os.ttyname(sys.stdout.fileno()))  #Log to standard output
driver = webdriver.PhantomJS(service_log_path=os.path.devnull) #Log/dev/Discard to null
driver.set_window_size(1024, 768)
driver.get('https://google.com/')
driver.save_screenshot('google.png')
find_element_by_id()
find_element_by_name()
find_element_by_xpath()
find_element_by_link_text()
find_element_by_partial_link_text() # <a>Specify the text enclosed in
find_element_by_tag_name()          #Specify the name of the html tag
find_element_by_class_name()
find_element_by_css_selector()

reference

8. Errors and Exceptions — Python 3.5.1 Documentation 12.6. sqlite3 — DB-API 2.0 interface to SQLite database — Python 3.5.1 documentation 14.2. configparser — Configuration file parser — Python 3.5.1 documentation 16.1. Os — Miscellaneous operating system interfaces — Python 3.5.1 documentation 29.1. sys — System parameters and functions — Python 3.5.1 documentation xxx format special methods, special fields »Python Snippets

Recommended Posts

Python memorandum
Python Memorandum 2
Python memorandum
python memorandum
Python memorandum
python memorandum
Python memorandum
Python basics memorandum
Python pathlib memorandum
Python memorandum (algorithm)
Python memorandum [links]
Python memorandum numbering variables
python memorandum (sequential update)
Python
Python basic memorandum part 2
[Python] Iterative processing_Personal memorandum
Memorandum @ Python OR Seminar
python memorandum super basic
Effective Python Learning Memorandum Day 15 [15/100]
Effective Python Learning Memorandum Day 6 [6/100]
Effective Python Learning Memorandum Day 12 [12/100]
Effective Python Learning Memorandum Day 9 [9/100]
Effective Python Learning Memorandum Day 8 [8/100]
About python beginner's memorandum function
Memorandum @ Python OR Seminar: matplotlib
[Python] SQLAlchemy error avoidance memorandum
Effective Python Learning Memorandum Day 14 [14/100]
Effective Python Learning Memorandum Day 1 [1/100]
Memorandum @ Python OR Seminar: Pulp
Effective Python Learning Memorandum Day 13 [13/100]
A memorandum about Python mock
Effective Python Learning Memorandum Day 3 [3/100]
Effective Python Learning Memorandum Day 5 [5/100]
Memorandum @ Python OR Seminar: Pandas
[python] Random number generation memorandum
Effective Python Learning Memorandum Day 4 [4/100]
Memorandum @ Python OR Seminar: scikit-learn
Effective Python Learning Memorandum Day 7 [7/100]
Effective Python Learning Memorandum Day 2 [2/100]
python parallel / asynchronous execution memorandum
kafka python
linux memorandum
Python basics ⑤
python + lottery 6
Python Summary
Built-in python
ABC memorandum [ABC159 C --Maximum Volume] (Python)
jinja2 memorandum
Python comprehension
Python technique
Python pywin32 (win32com) Excel operation memorandum
Studying python
Python 2.7 Countdown
Django memorandum
Python FlowFishMaster
Python service
python tips
python function ①
Python basics
Python memo
ufo-> python (3)