-
Notifications
You must be signed in to change notification settings - Fork 0
/
python_examples
250 lines (162 loc) · 6.72 KB
/
python_examples
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
##########################################################################################
##########################################################################################
### Python code that I've written to use as a reference for stuff I've forgotten ###
##########################################################################################
##########################################################################################
#############################################
#print with variables
#############################################
# best method, f-strings, python3 only
my_name = 'Jimmy'
print (f.'Hello, {my_name}')
# second best method, format strings, all versions
my_name = 'Jimmy'
print ('Hello, {}'.format(my_name))
#############################################
#dictionaries
#############################################
#! /usr/bin/env python3
# dictionary practice
birthdays = {'Luke Skywalker': '5/24/19', 'Obi-Wan Kenobi': '3/11/57', 'Darth Vader': '4/1/41'}
print(birthdays)
# print everything in a dictionary on separate lines using items() method
for i in birthdays.items():
print (i)
('Luke Skywalker', '5/24/19')
('Obi-Wan Kenobi', '3/11/57')
('Darth Vader', '4/1/41')
for name in 'Yoda', 'Darth Vader':
if name in birthdays:
print('{} is in the dictionary'.format(name))
else:
birthdays[name] = 'unknown'
print('{} has been added to the dictionary'.format(name))
print()
for name in sorted(birthdays):
print('{} {}'.format(name, birthdays[name]))
print()
del(birthdays['Darth Vader'])
for name in sorted(birthdays):
print('{} {}'.format(name, birthdays[name]))
#############################################
#user input #input
#############################################
#! /usr/bin/env python3
user_input = input('What? ')
print ('Your face is a {}!'.format(user_input))
#############################################
#functions #define functions
#############################################
#! /usr/bin/env python3
def multiply(num_1, num_2):
product = int(num_1) * int(num_2)
return product
first_num = input('What is the first number to multiply? ')
second_num = input('What is the second number to multiply? ')
answer = multiply(first_num, second_num)
print('Your answer is {}'.format(answer))
#############################################
#find in string #find non-regex
#############################################
#! /usr/bin/env python3
my_string = input('What is your string? ')
my_letter = input('What letter would you like to search for in your string? ')
position = my_string.find(my_letter)
if position == -1:
print ('{} was not found in {}'. format(my_letter, my_string))
else:
print('{} was first found in position {} of {}'.format(my_letter, position, my_string))
#############################################
#regex
#############################################
import re
string1= "test the stuff 1 and 2"
found_string = (re.search("test.*stuff", string1)).group()
>>>print found_string
>>>test the stuff
#capture groups (AKA subgroups), capture part of regex match instead of entire thing
import re
string2 = 'test more stuff A and B'
found_string = (re.search("more.*B", string2)).group()
captured_string = (re.search("more.*(stuff.*A).*B", string2)).group(1)
print (found_string)
>>> more stuff A and B
print (captured_string)
>>> stuff A
#############################################
#files #file input #file read #file write
#############################################
#read from file, close automatically when done (with open)
with open('mad_lib_1.txt', 'r') as file:
#print file.readlines()
for line in file.readlines():
print line
#read from one file and write to another, close automatically
with open('output.txt', 'w') as write_file, open('mad_lib_1.txt', 'r') as read_file:
for line in read_file.readlines():
write_file.write(line)
#############################################
#restful API calls
#############################################
import requests
resp = requests.get('https://swapi.co/api/people/1/') #make a GET Http request to a test api site with Star Wars info
resp_dict = resp.json() # unpack the json response into a dictionary
for i in resp_dict.items():
print (i) # print each key value pair in the dictionary on a separate line
('name', 'Luke Skywalker')
('height', '172')
('mass', '77')
('hair_color', 'blond')
('skin_color', 'fair')
('eye_color', 'blue')
('birth_year', '19BBY')
('gender', 'male')
('homeworld', 'https://swapi.co/api/planets/1/')
('films', ['https://swapi.co/api/films/2/', 'https://swapi.co/api/films/6/', 'https://swapi.co/api/films/3/', 'https://swapi.co/api/films/1/', 'https://swapi.co/api/films/7/'])
('species', ['https://swapi.co/api/species/1/'])
('vehicles', ['https://swapi.co/api/vehicles/14/', 'https://swapi.co/api/vehicles/30/'])
('starships', ['https://swapi.co/api/starships/12/', 'https://swapi.co/api/starships/22/'])
('created', '2014-12-09T13:50:51.644000Z')
('edited', '2014-12-20T21:17:56.891000Z')
('url', 'https://swapi.co/api/people/1/')
#############################################
#web scraping, simple with standard libraries
#############################################
from urllib.request import urlopen
url = "http://olympus.realpython.org/profiles/aphrodite"
html_page = urlopen(url)
html_text = html_page.read().decode("utf-8")
print(html_text)
#############################################
#web scraping, advanced with Beautiful Soup
#############################################
#############################################
#ssh, paramiko
#############################################
#! /usr/bin/env python3
# A generic Python SSH script to connect, run commands, and save output
# import paramako library for SSH connections
import paramiko
#set host to connect to, username, and password
ssh_hostname = '<name_or_IP'
ssh_username = '<user>'
ssh_password = '<password>'
# create ssh_connection variable for Paramiko connection, set it to automatically add new server SSH keys, set target and credentials from variables
ssh_connection =paramiko.SSHClient()
ssh_connection.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_connection.connect(hostname=ssh_hostname,username=ssh_username,password=ssh_password)
# connect to device, run command(s), save output to variables
stdin,stdout,stderr=ssh_connection.exec_command('ls')
# parse Python objects, save reslts to printable variables
stdout_output = stdout.read().decode('ascii')
stderr_output = stderr.read().decode('ascii')
# print output
print (f.'stderr: {stderr_output}')
print (f.'stdout: {stdout_output}')
#############################################
#datetime
#############################################
>>> import datetime
>>> print datetime.datetime.now()
2020-05-14 11:56:29.938464
>>>