در این تاپیک نمونه سورس های آموزشی " Python " قرار داده میشه .
لطفا از پرسیدن سوال و درخواست کد و برنامه خودداری کنید .
در این تاپیک نمونه سورس های آموزشی " Python " قرار داده میشه .
لطفا از پرسیدن سوال و درخواست کد و برنامه خودداری کنید .
به صورت زیر میتونید مدت زمانی که اجرای یک قطعه کد طول میکشه رو به دست بیارید :
import time;
T1= time.clock();
#Some code here ...
for i in range(100000):
print(i);
T2= time.clock();
ElapsedTime= T2-T1;
print(ElapsedTime);
سلام
چند روز پیش رفتم دنبال برنامه نویسی cgi تو python بعد خیلی برام جالب بود گفتم شاید دوستان علاقه داشته باشن
فقط باید تنظیمات apache رو برای cgi فعال کنید و بعد این فایل رو با مجوز اجرا بندازید تو تو پوشه ی cgi apache
اینم یه برنامه hello world
#!/usr/bin/python
import cgitb
cgitb.enable()
print "Content-Type: text/plain;charset=utf-8"
print "Hello World!"
ساعت باینری :
import os;
import time;
def IntToBinary(IntNumber):
return '{0:06b}'.format(IntNumber);
while 1:
os.system('cls');
H= time.localtime().tm_hour;
M= time.localtime().tm_min;
S= time.localtime().tm_sec;
HB= IntToBinary(H);
MB= IntToBinary(M);
SB= IntToBinary(S);
print(HB + " : " + MB + " : " + SB);
time.sleep(1);
# This is a guess the number game.
import random
guessesTaken = 0
number = random.randint(1, 20)
print('hi, I am thinking of a number between 1 and 20.')
while guessesTaken < 6:
print('Take a guess.') # There are four spaces in front of print.
guess = input()
guess = int(guess)
guessesTaken = guessesTaken + 1
if guess < number:
print('Your guess is too low.') # There are eight spaces in front of print.
if guess > number:
print('Your guess is too high.')
if guess == number:
break
if guess == number:
guessesTaken = str(guessesTaken)
print('Good job, '+'! You guessed my number in ' + guessesTaken + ' guesses!')
if guess != number:
number = str(number)
print('Nope. The number I was thinking of was ' + number)
arr = [1, 1]
print(arr[0])
while True:
print(arr[-1])
tmp = sum(arr)
arr.append(tmp)
del arr[0]
import ctypes
user32 = ctypes.windll.user32
screensize = user32.GetSystemMetrics(0), user32.GetSystemMetrics(1)
print screensize
دفترچه تلفن با قابلیت "درج" و "جستجو" ، در این سورس نکته های ریزی وجود داره که برای تازه کارها میتونه جالب باشه :
import os;
def Init():
print("\n.: Welcome to PhoneBook using Dictionaries :. \n");
print(".: Enter '+' to add new item and '?' to find it in list or 'e' to exit :. \n");
PhoneBook={};
while 1:
os.system('cls');
Init();
Statement= input("Enter your own work letter : ");
if Statement == "e":
break;
elif Statement == "+":
print("\nEnter name and phone number like the following :\n");
print(" Mojtaba:0123456\n");
Name_Phone= input(" ");
Name_Phone= Name_Phone.split(":");
PhoneBook[Name_Phone[0].lower()]= Name_Phone[1];
elif Statement == "?":
if len(PhoneBook) == 0:
input("Then phonebook is empty, Press enter to continue");
else:
Name= input("Enter name to search for it :");
Name= Name.lower();
if Name in PhoneBook:
print("\nThe phone number of ' %s ' is : %s" %(Name, PhoneBook[Name]));
input("\nPress enter to continue");
else:
print("Unknown statement");
آخرین ویرایش به وسیله Felony : یک شنبه 24 دی 1391 در 17:03 عصر
استفاده از DLL های Native ( تولید شده توسط زبان هایی مثل ++C و Delphi ) :
import ctypes;
MyDLL= ctypes.CDLL('C:\MyTestLibrary.dll');
MyDLL.TestFunction();
این هم یک نمونه DLL که برای تست کد بالا با Delphi نوشتم :
library MyTestLibrary;
uses
System.SysUtils,
System.Classes;
{$R *.res}
function TestFunction: Integer;
begin
Result := 123;
end;
exports
TestFunction;
begin
end.
import urllib.request
def URL2File(URL, FilePath):
urllib.request.urlretrieve(URL, FilePath)
نمونه استفاده :
URL2File('http://www.extremetech.com/wp-content/uploads/2012/12/Audi-A1.jpg', 'C:\\1.jpg')
import random
import os
Password= '';
while 1:
os.system('cls');
Password_Length= input("Enter password len to generate : ");
if int(Password_Length) == 0:
break;
for i in range(int(Password_Length)):
Password += chr(random.randint(33, 126));
print("\nThe generated password is : %s \n"%Password);
input("Press enter to generate new password or 0 to exit");
برای تولید دیتای رندوم برای مقاصد امنیتی (منجمله پسوردها) از os.urandom استفاده کنید نه از random.randint و امثالهم.
----------------------------
random.randint
...is completely unsuitable for cryptographic purposes
ترجمه: برای مقاصد رمزنگاری کاملا نامناسب است.
منبع: http://docs.python.org/2/library/random.html
---------------------------
os.urandom
Return a string of n random bytes suitable for cryptographic use.
ترجمه: رشته ای از n بایت رندوم مناسب برای استفادهء رمزنگاری را برمیگرداند.
منبع: http://docs.python.org/2/library/os.html#os.urandom
عنوان پست من رمزنگاری نبود ، عنوان تولید کننده رمز بود ( منظور تولید کننده کلمه عبور ) ، بحث cryptographic کجا و این کجا ... ، اون کدی که urandom تولید میکنه به درد کلمه عبور نمیخوره ، مگر پسورد FTP ناسا !برای تولید دیتای رندوم برای مقاصد امنیتی (منجمله پسوردها) از os.urandom استفاده کنید نه از random.randint و امثالهم.
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
در این نمونه کد با نحوه فراخوانی توابع API منجمله Callback Function ها در Python آشنا میشید :
import ctypes
# Imported API functions
EnumWindows = ctypes.windll.user32.EnumWindows
GetWindowText = ctypes.windll.user32.GetWindowTextW
GetWindowTextLength = ctypes.windll.user32.GetWindowTextLengthW
IsWindowVisible = ctypes.windll.user32.IsWindowVisible
# Enum's procedure
EnumProc = ctypes.WINFUNCTYPE(ctypes.c_bool, ctypes.POINTER(ctypes.c_int), ctypes.POINTER(ctypes.c_int))
Titles = [];
def foreach_window(hwnd, lParam):
if IsWindowVisible(hwnd):
WindowTextLength = GetWindowTextLength(hwnd)
buff = ctypes.create_unicode_buffer(WindowTextLength + 1)
GetWindowText(hwnd, buff, WindowTextLength + 1)
if buff.value != '':
Titles.append(buff.value)
return True
EnumWindows(EnumProc(foreach_window), 0)
for title in Titles:
print(title)
آخرین ویرایش به وسیله Felony : دوشنبه 25 دی 1391 در 12:09 عصر
سرور :
import asyncore
import socket
import os
import random
clients = {}
class MainServerSocket(asyncore.dispatcher):
def __init__(self, port):
asyncore.dispatcher.__init__(self)
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.bind(('',port))
self.listen(5)
def handle_accept(self):
newSocket, address = self.accept( )
clients[address] = newSocket
print("Connected from :", address)
SecondaryServerSocket(newSocket)
class SecondaryServerSocket(asyncore.dispatcher_with_sen d):
def handle_read(self):
os.system('color ' + str(random.randint(1, 10)))
message = self.recv(8192)
message = message.decode('utf-8')
print('Message : ', message)
if message:
every = clients.values()
for one in every:
one.send(bytes('Server : ' + message + '\n', 'utf-8'))
else:
self.close()
def handle_close(self):
print(self.getpeername() , ' disconnected')
one = self.getpeername()
del clients[one]
MainServerSocket(21567)
asyncore.loop()
کلاینت :
from socket import *
from threading import Thread
import sys
HOST = 'LocalHost'
PORT = 21567
BUFSIZE = 1024
Address = (HOST, PORT)
TCPClient = socket(AF_INET, SOCK_STREAM)
TCPClient.connect(Address)
def recv():
while True:
message = TCPClient.recv(BUFSIZE)
if not message:
sys.exit(0)
print(message.decode('utf-8'))
Thread(target=recv).start()
while True:
message = input()
if message:
TCPClient.send(bytes(message, 'utf-8'))
TCPClient.close()
import platform
print 'Version :', platform.python_version()
print 'Version tuple:', platform.python_version_tuple()
print 'Compiler :', platform.python_compiler()
print 'Build :', platform.python_build()
print 'Normal :', platform.platform()
print 'Aliased:', platform.platform(aliased=True)
print 'Terse :', platform.platform(terse=True)
print 'uname:', platform.uname()
print 'system :', platform.system()
print 'node :', platform.node()
print 'release :', platform.release()
print 'version :', platform.version()
print 'machine :', platform.machine()
print 'processor:', platform.processor()
print 'interpreter:', platform.architecture()
print '/bin/ls :', platform.architecture('/bin/ls')
بازی دوز:
class tic_toe(object):
"this is tic & toe game"
def __init__(self):
self.size=3
def run(self):
floor=['_']*self.size*self.size # game platform
# ------------------------
c=1
WhoAreU=''
# ----------------------
while True: # --game loop
if c%2==0:
ans=input('\t\tX: ')
if floor[ans-1]=='_':
floor[ans-1]='X'
WhoAreU='X'
else:
print ans,' already is entered'
continue
else:
ans=input('\t\tO: ')
if floor[ans-1]=='_':
floor[ans-1]='O'
WhoAreU='O'
else:
print ans,' already is entered'
continue
self.printf(floor,self.size)
# -----------------------
if self.examine2(floor)==True:
print '\t\t %s ARE WINNER \n' % WhoAreU
q=raw_input('\t\t Do uoy want ro continue? ')
if q=='y':
tic_toe('3x3').run()
return
else:
return
c+=1
# ---------------------------
if c>(3*3): # ending game or continue whene finishing
print 'DRAW...'
q=raw_input('Do uoy want ro continue? ')
if q=='y':
tic_toe().run()
return
else:
return
# --------------------------------------------------------------------------- END OF GAME LOOP and MAIN FUN()
# --------------------------------------------------------------------------- /\ /\ /\ /\ /\ /\ /\ /\ /\ /\ /\ /\ /\ /\ /\ /\
# \/ \/ \/ \/ \/ \/ \/ \/ \/ \/ \/ \/ \/ \/ \/ \/
# -------------------------------------------------------------------- printf FUN()
def printf(self,floor,size):
c=1
print '\n'
for i in floor:
print i,' ',
if c%size==0:
print '\n'
c+=1
# --------------------------------------------------------------------------
def examine2(self,floor):
winlist=[[0,1,2],[3,4,5],[6,7,8],[0,4,8],[2,4,6],[0,3,6],[1,4,7],[2,5,8]]
for i in winlist:
if floor[i[0]]==floor[i[1]] and floor[i[1]]==floor[i[2]]:
if floor[i[0]]!='_':
return True
return False
# ----------------------------------------------------
# ----------------------------------------------------
# ----------------------------------------------------
if __name__=="__main__":
t=tic_toe
t().run()
آخرین ویرایش به وسیله code_baz : پنج شنبه 26 بهمن 1391 در 14:06 عصر
یه کد خیلی قشنگ پر از نکات آموزنده برای تولید html
خیلی آموزنده هست
بدون هیچ ماژول اصافه ای:
اینم لینکش:
from string import Template
TAB = " "
class T(object):
""" A template object has a name, attributes and content.
The contents may contain sub template objects.
Attributes are kept in order.
The only things one has to remember:
* Attributes clashing with python keywords must be suffixed with a '_'.
* Attribute names should not start with an underscore '_'
* use the '<' operator to add content to a template object.
"""
def __init__(self, name = None):
self.__name = name
self.__multi_line = False
self.__contents = []
self.__attributes = []
def __open(self, level = -1, **namespace):
out = ["{0}<{1}".format(TAB * level, self.__name)]
for (name, value) in self.__attributes:
out.append(' {0}="{1}"'.format(name, value))
out.append(">")
if self.__multi_line:
out.append("\n")
templ = ''.join(out)
txt = Template(templ).substitute(namespace)
return txt
def __close(self, level = -1, **namespace):
if self.__multi_line:
txt = "\n{0}</{1}>\n".format(TAB * level, self.__name)
else:
txt = "</{0}>\n".format(self.__name)
return txt
# public API
def _render(self, level = -1, **namespace):
out = []
out_contents = []
contents = self.__contents
for item in contents:
if item is None:
continue
if type(item) is T:
self.__multi_line = True
out_contents.append(item._render(level = level + 1, **namespace))
else:
out_contents.append("{0}{1}".format(TAB * level, Template(item).substitute(namespace)))
#out_contents.append("{0}".format(Template(item).s ubstitute(namespace)))
txt_contents = ''.join(out_contents)
if not self.__multi_line:
txt_contents = txt_contents.strip()
else:
txt_contents = txt_contents.rstrip()
if self.__name:
out.append(self.__open(level, **namespace))
out.append(txt_contents)
out.append(self.__close(level, **namespace))
else:
out.append(txt_contents)
return ''.join(out)
def __getattr__(self, name):
t = self.__class__(name)
self < t
return t
def __setattr__(self, name, value):
if name.startswith('_'):
self.__dict__[name] = value
else:
## everything else is an element attribute
## strip trailing underscores
self.__attributes.append((name.rstrip('_'), value))
def _set(self, name, value):
""" settings of attributes when attribure name is not a valid python
identifier.
"""
self.__attributes.append((name.rstrip('_'), value))
def __lt__(self, other):
self.__contents.append(other)
return self
def __call__(self, _class = None, _id = None):
if _class:
self.__attributes.append(('class', _class))
if _id:
self.id = _id
return self
## with interface
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, exc_traceback):
return False
def example():
doc = T()
doc < """<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
\n"""
## we can create a second template object and add it to any other template object.
footer = T()
with footer.div('footer', 'foot1').h3.p.pre as pre:
pre.style = 'some style'
pre < 'Copyright T inc'
with doc.html as html:
with html.head as head:
## element attributes are set the usual way.
head.title = 'Good morning ${name}!'
with html.body as body:
## there is no need to use the with statement. It is useful for
## provide=ing structure and clarity to the code.
body.h3('main') < "Header 3"
## with statement
with body.p as p:
p.class_ ="some class"
p < "First paragraph"
## same as above but without the 'with' statement
body.p("some class") < "First paragraph"
with body.ul as ul:
for i in range(10):
ul.li < str(i)
with body.p as p:
p < "test inline html"
p.b("bold")
## append a template object
body < footer
return doc
if __name__ == "__main__":
doc = example()
html = doc._render(name = 'Clio')
print html
http://code.activestate.com/recipes/...in=lang-python
سلام
آموزش PyQt5 را در اين سايت ببينيد
www.python.cum.ir