Python -Threading
Jan. 12, 2016, 11:08 a.m.
Python Threading Örneği:
#!/usr/bin/env python2
import threading
import time
class MyThread (threading.Thread):
def __init__(self, thread_id, name, some_more_variable):
threading.Thread.__init__(self)
self.thread_id = thread_id
self.name = name
self.some_more_variable = some_more_variable
self.daemon = True # Ana islem sonlandiginda thread'de sonlanacak
def run(self):
# thread islemi
pass
# Yeni threadler yarat
thread1 = MyThread(1, "Thread-1","other_variable")
thread2 = MyThread(2, "Thread-2","other_variable")
# Yeni threadleri baslat
thread1.start()
thread2.start()
sleep(50) # Ana thread. Buraya kod gelecek
# threadler bir sekilde kesilirse sonlandırıldığını garantilememiz gerekiyor
thread1.join()
thread2.join()
Fonksiyonları:
- run(): thread.start() ile tetiklenen fonksiyon. Asıl işi yapan method burası
- start(): thread.start() , multhreading başlatır ve run() methodunu çağırır.
- join([n]): n saniye sonra thread'i sonlandırır
- isAlive(): thread hala çalışıyormu kontrol eder
- getName(): thread'in adını döndürür
- setName(): thread'in adını set eder
Python - String Operations
Jan. 7, 2016, 10:26 a.m.
Fastest way to construct a string :
text = "%d,C100,%s,,%s,V101,%s,0,1,#" % (self.message_counter, str(self.device_id), time_str, data_list[5]))
Rounding a float:
'%.5f' % .12345678
Python - File Operations
Jan. 2, 2016, 12:22 a.m.
Read file and split by lines :
with open("test.txt", "a") as myfile:
myfile.write("appended text")
Open Modes:
Modes | Description |
---|---|
r | Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the default mode. |
rb | Opens a file for reading only in binary format. The file pointer is placed at the beginning of the file. This is the default mode. |
r+ | Opens a file for both reading and writing. The file pointer placed at the beginning of the file. |
rb+ | Opens a file for both reading and writing in binary format. The file pointer placed at the beginning of the file. |
w | Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing. |
wb | Opens a file for writing only in binary format. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing. |
w+ | Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing. |
wb+ | Opens a file for both writing and reading in binary format. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing. |
a | Opens a file for appending. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing. |
ab | Opens a file for appending in binary format. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing. |
a+ | Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing. |
ab+ | Opens a file for both appending and reading in binary format. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing. |
Python Execute Shell Commands
Dec. 22, 2014, 9:55 p.m.
Renkli shell çıktıları için :
# -*- coding: utf-8 -*-
__author__ = 'ozgur'
__creation_date__ = '27.01.2013' '02:16'
__RED = '\033[91m'
__GREEN = '\033[92m'
__YELLOW = '\033[93m'
__BLUE = '\033[94m'
__PINK = '\033[95m'
__CYAN = '\033[96m'
__WHITE = '\033[97m'
__YELLOW = '\033[93m'
__ENDC = '\033[0m'
__DEFAULT = "\033[99m"
def printComment(text):
return __GREEN + text + __ENDC
def printMenu(text):
return __YELLOW + text + __ENDC
def printInfo(text):
return __PINK + text + __ENDC
Renklendirdiğimiz çıktıyı ekrana echo ettirdiğimizde bash'in kendi içine gömülü renklendirmesini kullanarak çıktıları ekrana yazdırabiliriz
Bir diğer konu ise.Python üzerinde komut satırı işletimi ve process yönetimi için subprocess adında harika bir kütüphane var. Kullanım örnekleri:
Çıktıyı bir değişkene atamak için :
import commands
output = commands.getstatusoutput('ls -alh')
Çıktıyı shell e yönlendirmek için :
command = "ls -alh"
subprocess.call([command],shell=True)
Eğer işlemimiz uzun sürüyorsa ve çıktıları anlık olarak adım adım takip edeceksek çıktıyı sterror a pieline olarak bağlamamız gerekiyor. Örneğin netstat için:
#!/usr/bin/python
import subprocess
## command to run - tcp only ##
cmd = "/usr/sbin/netstat -p tcp -f inet"
## run it ##
p = subprocess.Popen(cmd, shell=True, stderr=subprocess.PIPE)
## But do not wait till netstat finish, start displaying output immediately ##
while True:
out = p.stderr.read(1)
if out == '' and p.poll() != None:
break
if out != '':
sys.stdout.write(out)
sys.stdout.flush()