Skip to content

Instantly share code, notes, and snippets.

@unitycoder
Last active April 25, 2016 08:59
Show Gist options
  • Select an option

  • Save unitycoder/24756e9fa438a8772c1c8743c4f3fcb4 to your computer and use it in GitHub Desktop.

Select an option

Save unitycoder/24756e9fa438a8772c1c8743c4f3fcb4 to your computer and use it in GitHub Desktop.
PythonNotes
# http://stackoverflow.com/a/18416308
from threading import Thread
import time
class MyClass(Thread):
def __init__(self, name):
super(MyClass, self).__init__()
#self.daemon = True
self.cancelled = False
self.name = name
def run(self):
while not self.cancelled:
self.update()
time.sleep(1)
def cancel(self):
"""End this timer thread"""
self.cancelled = True
# main thread loop
def update(self):
"""Update the counters"""
print self.name+"\n"
#pass
threadList = []
# start new thread
thread1 = MyClass("Thread#1")
thread1.start()
# take it to list
threadList.append(thread1)
# start new thread
thread2 = MyClass("Thread#2")
thread2.start()
# take it to list
threadList.append(thread2)
# MAIN LOOP
while True:
try:
print "--MAINTHREAD--\n"
time.sleep(1)
except KeyboardInterrupt: #close on ctrl+c
for t in threadList:
t.cancel()
break
print "*** FINISHED ***"
# get ip address of this pc
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("google.com",80))
myIP = s.getsockname()[0]
print myIP
s.close()
#print to same line, add comma
print 'a',
# iterate numpy array
for x in np.nditer(A):
print x,
# int to bytes
b = bytes(chr(random.randint(0,255)))
# use global variable inside class
myvar=100
class ...
global myvar
print myvar #100
# using ATOM editor/ide
- install atom
- install packages "script" and "python python-tools" (optional)
- if script plugin cannot find python to run, add python folder to Windows PATH enviroment variable
- Run script from Packages/Scripts/Run script
# join?
A = 'asdf'
B = 123
server_address = (A, B)
# clamp
numpy.clip(val,min,max)
# exit with ctrl+c
while True:
try:
print "--loop--\n"
time.sleep(1)
except KeyboardInterrupt:
print "bye"
sys.exit()
# for loop with custom step : https://wiki.python.org/moin/ForLoop
def my_range(start, end, step):
while start <= end:
yield start
start += step
for x in my_range(1, 10, 0.5):
print x
# check if object in list, remove if yes
if thing in some_list: some_list.remove(thing)
# check if list contains
if myItem in list:
# do something
# stock blocking socket connection wait function
#socket.shutdown(socket.SHUT_WR) # doesnt work
# or http://stackoverflow.com/a/10090348 # doesnt work
# works, connect to it, then close
http://stackoverflow.com/a/16736227
# init dictionary
dictionary = {}
# add item
dictionary['key'] = "value"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment