Tips
Find all installed modules
help("modules");
Virtual Environment
With virtualenv and virtualenvwrapper
# Installing virtualenv and virtualenvwrapper
sudo pip install virtualenv virtualenvwrapper
# Update the profile ~/.bashrc
# Add the following lines
# Python virtualenv and virtualenvwrapper
export WORKON_HOME=$HOME/.virtualenvs
export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3
source /usr/local/bin/virtualenvwrapper.sh
# Reload the profile
source ~/.bashrc
# Creating python virtual environment
# The py3cv3 is a self-defined name
mkvirtualenv py3cv3 -p python3
# Enter the specified virtual environment
workon py3cv3
# Exit the the specified virtual environment
deactivate
# List all of the environments.
lsvirtualenv
# Remove an environment
rmvirtualenv py3cv3
Timestamp
timestamp = datetime.datetime.now()
print("It is {}".format(timestamp.strftime("%A %d %B %Y %I:%M:%S%p")))
Math
total += 1
If-then
# Boolean, none
if motion is not None:
if not flag:
# Number
if delay > 0:
if delay == 0:
if total > frameCount:
# String
if "blue" in style:
if authors.startswith('['):
authors = authors.lstrip('[').rstrip(']')
def doi_url(d): return f'http://{d}' if d.startswith('doi.org') else f'http://doi.org/{d}'
Command Arguments
# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--interval", required=False,
help="Seconds to Interval (Default:30)", default="30", type=int)
ap.add_argument("-o", "--output", required=False,
help="Path to Output Logs (Default:std-out)")
args = vars(ap.parse_args())
# Usage
intv = args["interval"]
logfile = args["output"]
JSON
JSON to dict
json.loads
用來轉換資料; json.load
用來讀檔。
import json
person = '{"name": "Bob", "languages": ["English", "French"]}'
person_dict = json.loads(person)
# Output: {'name': 'Bob', 'languages': ['English', 'French']}
print( person_dict)
# Output: ['English', 'French']
print(person_dict['languages'])
Dict to JSON
import json
person_dict = {'name': 'Bob',
'age': 12,
'children': None
}
person_json = json.dumps(person_dict)
# Output: {"name": "Bob", "age": 12, "children": null}
print(person_json)
Read JSON file
import json
with open('path_to_file/person.json', 'r') as f:
data = json.load(f)
# Output: {'name': 'Bob', 'languages': ['English', 'French']}
print(data)
Write JSON file
json.dump
用來寫檔案; json.dumps
用來轉換資料。
import json
person_dict = {"name": "Bob",
"languages": ["English", "French"],
"married": True,
"age": 32
}
with open('person.txt', 'w') as json_file:
json.dump(person_dict, json_file)
Print JSON
import json
person_string = '{"name": "Bob", "languages": "English", "numbers": [2, 1.6, null]}'
# Getting dictionary
person_dict = json.loads(person_string)
# Pretty Printing JSON string back
print(json.dumps(person_dict, indent = 4, sort_keys=True))
Access JSON
import json
json_data = '''
{
"students": [
{
"name": "David",
"age": 19,
"grades": {
"math": 90,
"english": 87
}
},
{
"name": "Harry",
"age": 21,
"grades": {
"math": 85,
"english": 95
}
}
]
}
'''
# Parse JSON Data
data = json.loads(json_data)
print(# To access a large dataset we can use `for loop`
for student in data['students'"students"]:
name = student["name"]
math_mark = student["grades"][0]"math"]
english_mark = student["grades"]['name'"english"])
average_mark = (math_mark + english_mark) / 2
print(data['students'][0]['grades']f"{name}, Avarage Marks: {average_mark:.2f}")
# Output:
# DavidDavid, Average Marks: 88.50
# {'math':Harry, 90,Average 'english':Marks: 87}90.00