مدرسه زبان برنامه‌نویسی PYTHON

وبلاگی جهت معرفی - آموزش و تحلیل زبان برنامه نویسی ‍پایتون

مدرسه زبان برنامه‌نویسی PYTHON

وبلاگی جهت معرفی - آموزش و تحلیل زبان برنامه نویسی ‍پایتون

۷ مطلب با کلمه‌ی کلیدی «مدرسه پایتون» ثبت شده است

این بدان معناست که هر زمان که نمونه_function را فراخوانی می کنیم، اساساً تابع add_one تعریف شده در دکوراتور را فراخوانی می کنیم.

 

هنگام استفاده از دکوراتورها، ممکن است بخواهیم تابع تزئین شده زمانی که از تابع wrapper فراخوانی می شود، آرگومان ها را دریافت کند.

به عنوان مثال، اگر تابعی داشته باشیم که به دو پارامتر نیاز دارد و مجموع آنها را برمی گرداند:

def add(a,b):
    return a + b

print(add(1,2)) # 3

و اگر از دکوراتور استفاده کنیم که 1 به خروجی اضافه کند:

 

def add_one_decorator(func):
    def add_one():
        value = func()
        return value + 1

    return add_one

@add_one_decorator
def add(a,b):
    return a + b

add(1,2)
# TypeError: add_one_decorator.<locals>.add_one() takes 0 positional arguments but 2 were given

هنگام انجام این کار، با یک خطا مواجه می شویم: تابع wrapper (add_one) هیچ آرگومان نمی گیرد اما ما دو آرگومان ارائه می دهیم.

برای رفع این مشکل، باید هر آرگومان دریافتی از add_one را هنگام فراخوانی آن به تابع تزئین شده منتقل کنیم:

def add_one_decorator(func):
    def add_one(*args, **kwargs):
        value = func(*args, **kwargs)
        return value + 1

     return add_one

 @add_one_decorator
 def add(a,b):
     return a+b

 print(add(1,2)) # 4

ما از *args و **kwargs استفاده می کنیم تا نشان دهیم که تابع add_one wrapper باید بتواند هر مقدار از آرگومان های موقعیتی (args) و آرگومان های کلمه کلیدی (kwargs) را دریافت کند.

args لیستی از تمام کلمات کلیدی موقعیتی داده شده خواهد بود، در این مورد [1،2].

kwargs یک فرهنگ لغت با کلیدها به عنوان آرگومان های کلیدواژه مورد استفاده و مقادیر به عنوان مقادیر اختصاص داده شده به آنها، در این مورد یک فرهنگ لغت خالی خواهد بود.

نوشتن func(*args، **kwargs) نشان می‌دهد که می‌خواهیم func را با همان آرگومان‌های موقعیتی و کلیدواژه‌ای که دریافت شد، فراخوانی کنیم.

این تضمین می کند که همه آرگومان های موقعیتی و کلیدواژه ارسال شده به تابع تزئین شده به تابع اصلی منتقل می شوند.

چرا دکوراتورها در پایتون مفید هستند؟ نمونه کد واقعی
اکنون که نگاهی به دکوراتورهای پایتون انداختیم، بیایید چند نمونه واقعی از مفید بودن دکوراتورها را ببینیم.

ورود به سیستم
هنگام ساخت برنامه های بزرگتر، اغلب مفید است که گزارش هایی از عملکردهایی که با اطلاعات اجرا شده اند، مانند اینکه چه آرگومان هایی استفاده شده اند، و چه تابعی در طول زمان اجرای برنامه بازگردانده است، مفید است.

این می‌تواند برای عیب‌یابی و اشکال‌زدایی در مواقعی که مشکل پیش می‌آید بسیار مفید باشد، تا به شما کمک کند تا مشخص کنید مشکل از کجا منشأ گرفته است. حتی اگر برای اشکال زدایی نباشد، ورود به سیستم می تواند برای نظارت بر وضعیت برنامه شما مفید باشد.

در اینجا یک مثال ساده از اینکه چگونه می توانیم یک لاگر ساده (با استفاده از بسته لاگ داخلی پایتون) ایجاد کنیم تا اطلاعات مربوط به برنامه خود را در حین اجرا در فایلی به نام main.log ذخیره کنیم:

ثبت ورود به سیستم

import logging

def function_logger(func):
    logging.basicConfig(level = logging.INFO, filename="main.log")
    def wrapper(*args, **kwargs):
        result = func(*args, **kwargs)
        logging.info(f"{func.__name__} ran with positional arguments: {args} and keyword arguments: {kwargs}. Return value: {result}")
        return result

    return wrapper

@function_logger
def add_one(value):
    return value + 1

print(add_one(1))

هر زمان که تابع add_one اجرا شود، یک گزارش جدید به فایل main.log اضافه می شود:

INFO:root:add_one ran with positional arguments: (1,) and keyword arguments: {}. Return value: 2

 

Cashing

اگر برنامه ای داشته باشیم که نیاز به اجرای یک تابع چندین بار با آرگومان های یکسان داشته باشد و مقدار یکسان را برگرداند، می تواند به سرعت ناکارآمد شود و منابع غیر ضروری را اشغال کند.

برای جلوگیری از این امر، ذخیره آرگومان های استفاده شده و مقدار بازگشتی تابع در هر زمان که فراخوانی می شود، می تواند مفید باشد و اگر قبلاً تابع را با همان آرگومان ها فراخوانی کرده ایم، به سادگی از مقدار برگشتی مجددا استفاده کنیم.

در پایتون، این را می توان با استفاده از دکوراتور @lru_cache از ماژول functools که با پایتون نصب می شود، پیاده سازی کرد.

LRU به Least Recently Used اشاره دارد، به این معنی که هر زمان که تابع فراخوانی شد، آرگومان های استفاده شده و مقدار بازگشتی ذخیره می شوند. اما به محض اینکه تعداد این ورودی ها به حداکثر اندازه رسید که به طور پیش فرض 128 است، کمترین ورودی اخیر حذف خواهد شد.

from functools import lru_cache

@lru_cache
def fibonacci(n):
    if n <= 1:
        return n
    return fibonacci(n - 1) + fibonacci(n - 2)

در این مثال، تابع فیبوناچی آرگومان n را می گیرد و اگر کمتر از 1 باشد، n ​​را برمی گرداند، در غیر این صورت مجموع تابع فراخوانی شده با n-1 و n-2 را برمی گرداند.

بنابراین، اگر تابع با n=10 فراخوانی شود، 55 را برمی گرداند:

print(fibnoacci(10))
# 55

در این حالت وقتی تابع fibonacci(10) را صدا می زنیم، تابع fibonacci(9) و fibonacci(8) را صدا می کند و به همین ترتیب تا زمانی که به 1 یا 0 برسد.

اگر بخواهیم از این تابع بیش از یک بار استفاده کنیم:

fibonacci(50)
fibonacci(100)

ما می توانیم از حافظه پنهان ورودی هایی که ذخیره شده اند استفاده کنیم. بنابراین وقتی فیبوناچی (50) را صدا می زنیم، می تواند پس از رسیدن به 10، فراخوانی تابع فیبوناچی را متوقف کند و هنگامی که ما فیبوناچی (100) را صدا می زنیم، می تواند پس از رسیدن به 50، فراخوانی تابع را متوقف کند و برنامه را بسیار کارآمدتر می کند.

این مثال‌ها یک چیز مشترک دارند و آن این است که پیاده‌سازی آن‌ها برای توابع از قبل موجود در پایتون بسیار آسان است. نیازی نیست کد خود را تغییر دهید یا به صورت دستی تابع خود را در دیگری بپیچید.

امکان استفاده ساده از نحو @، استفاده از ماژول ها و بسته های اضافی را آسان می کند.

خلاصه
دکوراتورهای پایتون این امکان را به شما می دهد که بدون هیچ زحمتی عملکردها را بدون نیاز به تغییر آنها گسترش دهید. در این آموزش، نحوه کار دکوراتورها را یاد گرفتید و نمونه هایی از موارد استفاده از آنها را مشاهده کردید.

اگر از محتوای آموزشی من لذت می برید، بلاگ من را برای محتوای بیشتر پایتون بررسی کنید.

همیشه در حال یادگیری. پیروز و برقرار باشید - سعید دامغانیان

۰ نظر موافقین ۰ مخالفین ۰ ۲۹ دی ۰۳ ، ۱۷:۳۱
سعید دامغانیان

Tuple ها به لیستها بسیار شبیه هستند، به جز اینکه Tuple ها غیرقابل تغییر هستند .
همچنین، آنها با استفاده از پرانتز، به جای براکت مربعی، ایجاد می شوند.
مثال:

words = ("spam", "eggs", "sausages",)

شما می توانید با مقادیر خود در مقیاس به همان اندازه که با لیست ها دسترسی داشتید دسترسی پیدا کنید:

print(words[0])

تلاش برای تخصیص یک مقدار در یک Tuple، یک TypeError را ایجاد می کند.

words[1] = "cheese"

خروجی:

>>>
TypeError: 'tuple' object does not support item assignment
>>>

نکته:مانند لیست ها و dictionary ها، tuple ها را می توان در داخل یکدیگر قرار داد.

tuple ها را می توان فقط با جدا کردن مقادیر با کاما و بدون پرانتز ایجاد کرد.
مثال:

my_tuple = "one", "two", "three"
print(my_tuple[0])

خروجی:

>>>
one
>>>

یک tuple خالی با استفاده از یک جفت پرانتز خالی ایجاد می شود.

tpl = ()

نکته:tuple ها سریعتر از لیست ها هستند اما قابل تغییر نیستند.

 

 

۰ نظر موافقین ۰ مخالفین ۰ ۲۸ شهریور ۰۳ ، ۲۱:۰۴
سعید دامغانیان

دانلود رایگان کتاب آموزشی زبان برنامه نویسی پایتون

به زبان انگلیسی #درخواستی_شما

به درخواست شما دوستان و همراهان عزیز رادیو صدای ققنوس

کتاب آموزش زبان برنامه نویسی پایتون نسخه پنجم (جدیدترین نسخه)

از سری کتابهای برگزیده زبان پایتون را در اینجا آپلود میکنم.

همیشه در حال یادگیری و پیروز باشید. #سعید_دامغانیان

 

رادیو صدای ققنوس | زبان برنامه نویسی پایتون

لینک دسترسی به کتاب

۲ نظر موافقین ۰ مخالفین ۰ ۲۸ شهریور ۰۳ ، ۲۰:۵۳
سعید دامغانیان

کد زیر یک عدد  رو از ورودی میگیره و جمله خواسته شده  سری فیبونانچی رو چاپ میکنه. دقت کنید که به صورت بازگشتی نوشته شده. سعی کنید روش غیر بازگشتی همین کد رو شما بنویسید.


#Programmer : Saeed Damghanian

#Web : Pyschool.blg.ir


# Function for nth Fibonacci number 

  

def Fibonacci(n): 

    if n<0: 

        print("Incorrect input") 

    # First Fibonacci number is 0 

    elif n==1: 

        return 0

    # Second Fibonacci number is 1 

    elif n==2: 

        return 1

    else: 

        return Fibonacci(n-1)+Fibonacci(n-2) 

  

# Driver Program 


n=int(input("Pleas Enter n: "))  

print(Fibonacci(n)) 

  


#------------Telegram: @Ghoghnous_Iran-----------------------




b444745_Untitled.png

۲ نظر موافقین ۰ مخالفین ۰ ۳۰ تیر ۹۸ ، ۰۶:۳۹
سعید دامغانیان

برنامه ای نوشتم که تعدادی عدد رو داخل خود برنامه تعریف کرده و ســــپس با روش مرتب سازی حبابی مرتبشون کنه. حالا شما سعی کنید برنامه ای بنویسید که همین اعداد رو از ورودی گرفته و مرتب کنه. میتونید یک شرط بگذارید که اگه کاربر کاراکتر خاصی رو وارد کرد به معنای پایان اعداد  وارد شده باشه. یا میتونید اعداد رو یکجا بگیرید و پردازش کنید. اگه سوالی بود در خدمت هستم.


#Programmer : Saeed Damghanian

#Web : Pyschool.blg.ir


def bubbleSort(arr):

    n = len(arr)

 

    # Traverse through all array elements

    for i in range(n):

 

        # Last i elements are already in place

        for j in range(0, n-i-1):

 

            # traverse the array from 0 to n-i-1

            # Swap if the element found is greater

            # than the next element

            if arr[j] > arr[j+1] :

                arr[j], arr[j+1] = arr[j+1], arr[j]

 

# Driver code to test above

arr = [64, 34, 25, 12, 22, 11, 90]

 

bubbleSort(arr)

 

print ("Sorted array is:")

for i in range(len(arr)):

    print ("%d" %arr[i])


#------------Telegram: @Ghoghnous_Iran-----------------------



a887838_Untitled.png


۰ نظر موافقین ۰ مخالفین ۰ ۳۰ تیر ۹۸ ، ۰۶:۲۸
سعید دامغانیان

برنامه زیر ضرائب معادله درجه 2 را گرفته و معادله را حل نموده و جوابهای معادله را در صورت حقیقی بودن نمایش می‌دهد. سعی کنید برنامه‌ای بنویسید که جوابهای موهمومی معادله را نیز محاسبه و چاپ کند.


#Programmer : Saeed Damghanian

#Web : Pyschool.blg.ir


import math

a=int(input("Please Enter a: "))

b=int(input("Please Enter b: "))

c=int(input("Please Enter c: "))

delta=b*b-4*a*c

if delta==0 :

    x=(-b + math.sqrt(delta))

    print("Moadele Yek javab darad. X=",x)

elif delta<0:

    print("Moadele javabe haghighi nadarad!")

else :    

    x1=(-b + math.sqrt(delta))/(2*a)

    x2=(-b - math.sqrt(delta))/(2*a)

    print("Moadele 2 javab darad.\n X1= ",x1, "\nX2= " , x2)


#------------Telegram: @Ghoghnous_Iran-----------------------


 

h909262_Untitled.png

۱ نظر موافقین ۰ مخالفین ۰ ۳۰ تیر ۹۸ ، ۰۶:۰۵
سعید دامغانیان

در این پست آموزشی قصد دارم که ارسال ُ نوشتن و ویرایش یک پست الکترونیک را با هم ببینیم و همچنین بعد با پروتکلها و استاندارهایی همچون MIME  و ارسال نامه به این سبک را آموزش دهم. با من (سعید دامغانیان) همراه باشید...

در قطعه کد زیر اولاْ ارسال یک ایمیل ساده را بررسی کنید :

# Import smtplib for the actual sending function
import smtplib

# Import the email modules we'll need
from email.message import EmailMessage

# Open the plain text file whose name is in textfile for reading.
with open(textfile) as fp:
    # Create a text/plain message
    msg = EmailMessage()
    msg.set_content(fp.read())

# me == the sender's email address
# you == the recipient's email address
msg['Subject'] = 'The contents of %s' % textfile
msg['From'] = me
msg['To'] = you

# Send the message via our own SMTP server.
s = smtplib.SMTP('localhost')
s.send_message(msg)
s.quit()

حال با استاندارد RFC822 آشنا شده و سپس کد زیر را بررسی کنید :

# Import the email modules we'll need
from email.parser import BytesParser, Parser
from email.policy import default

# If the e-mail headers are in a file, uncomment these two lines:
# with open(messagefile, 'rb') as fp:
#     headers = BytesParser(policy=default).parse(fp)

#  Or for parsing headers in a string (this is an uncommon operation), use:
headers = Parser(policy=default).parsestr(
        'From: Foo Bar <user@example.com>\n'
        'To: <someone_else@example.com>\n'
        'Subject: Test message\n'
        '\n'
        'Body would go here\n')

#  Now the header items can be accessed as a dictionary:
print('To: {}'.format(headers['to']))
print('From: {}'.format(headers['from']))
print('Subject: {}'.format(headers['subject']))

# You can also access the parts of the addresses:
print('Recipient username: {}'.format(headers['to'].addresses[0].username))
print('Sender name: {}'.format(headers['from'].addresses[0].display_name))

حال نوبت رسیده کمی فراتر رفته و به استاندارد MIME بپردازیم. نوبت شماست ...

# Import smtplib for the actual sending function
import smtplib

# And imghdr to find the types of our images
import imghdr

# Here are the email package modules we'll need
from email.message import EmailMessage

# Create the container email message.
msg = EmailMessage()
msg['Subject'] = 'Our family reunion'
# me == the sender's email address
# family = the list of all recipients' email addresses
msg['From'] = me
msg['To'] = ', '.join(family)
msg.preamble = 'You will not see this in a MIME-aware mail reader.\n'

# Open the files in binary mode.  Use imghdr to figure out the
# MIME subtype for each specific image.
for file in pngfiles:
    with open(file, 'rb') as fp:
        img_data = fp.read()
    msg.add_attachment(img_data, maintype='image',
                                 subtype=imghdr.what(None, img_data))

# Send the email via our own SMTP server.
with smtplib.SMTP('localhost') as s:
    s.send_message(msg)

در قطعه کد زیر فصد داریم محتویات یک دایرکتوری را به استاندارد MIME ارسال کنیم...

#!/usr/bin/env python3

"""Send the contents of a directory as a MIME message."""

import os
import smtplib
# For guessing MIME type based on file name extension
import mimetypes

from argparse import ArgumentParser

from email.message import EmailMessage
from email.policy import SMTP


def main():
    parser = ArgumentParser(description="""\
Send the contents of a directory as a MIME message.
Unless the -o option is given, the email is sent by forwarding to your local
SMTP server, which then does the normal delivery process.  Your local machine
must be running an SMTP server.
""")
    parser.add_argument('-d', '--directory',
                        help="""Mail the contents of the specified directory,
                        otherwise use the current directory.  Only the regular
                        files in the directory are sent, and we don't recurse to
                        subdirectories.""")
    parser.add_argument('-o', '--output',
                        metavar='FILE',
                        help="""Print the composed message to FILE instead of
                        sending the message to the SMTP server.""")
    parser.add_argument('-s', '--sender', required=True,
                        help='The value of the From: header (required)')
    parser.add_argument('-r', '--recipient', required=True,
                        action='append', metavar='RECIPIENT',
                        default=[], dest='recipients',
                        help='A To: header value (at least one required)')
    args = parser.parse_args()
    directory = args.directory
    if not directory:
        directory = '.'
    # Create the message
    msg = EmailMessage()
    msg['Subject'] = 'Contents of directory %s' % os.path.abspath(directory)
    msg['To'] = ', '.join(args.recipients)
    msg['From'] = args.sender
    msg.preamble = 'You will not see this in a MIME-aware mail reader.\n'

    for filename in os.listdir(directory):
        path = os.path.join(directory, filename)
        if not os.path.isfile(path):
            continue
        # Guess the content type based on the file's extension.  Encoding
        # will be ignored, although we should check for simple things like
        # gzip'd or compressed files.
        ctype, encoding = mimetypes.guess_type(path)
        if ctype is None or encoding is not None:
            # No guess could be made, or the file is encoded (compressed), so
            # use a generic bag-of-bits type.
            ctype = 'application/octet-stream'
        maintype, subtype = ctype.split('/', 1)
        with open(path, 'rb') as fp:
            msg.add_attachment(fp.read(),
                               maintype=maintype,
                               subtype=subtype,
                               filename=filename)
    # Now send or store the message
    if args.output:
        with open(args.output, 'wb') as fp:
            fp.write(msg.as_bytes(policy=SMTP))
    else:
        with smtplib.SMTP('localhost') as s:
            s.send_message(msg)


if __name__ == '__main__':
    main()
در اینجا طریقه باز کردن ایمیل دریافتی مشابه بالا را در همان استاندارد بررسی خواهیم نمود 
#!/usr/bin/env python3

"""Unpack a MIME message into a directory of files."""

import os
import email
import mimetypes

from email.policy import default

from argparse import ArgumentParser


def main():
    parser = ArgumentParser(description="""\
Unpack a MIME message into a directory of files.
""")
    parser.add_argument('-d', '--directory', required=True,
                        help="""Unpack the MIME message into the named
                        directory, which will be created if it doesn't already
                        exist.""")
    parser.add_argument('msgfile')
    args = parser.parse_args()

    with open(args.msgfile, 'rb') as fp:
        msg = email.message_from_binary_file(fp, policy=default)

    try:
        os.mkdir(args.directory)
    except FileExistsError:
        pass

    counter = 1
    for part in msg.walk():
        # multipart/* are just containers
        if part.get_content_maintype() == 'multipart':
            continue
        # Applications should really sanitize the given filename so that an
        # email message can't be used to overwrite important files
        filename = part.get_filename()
        if not filename:
            ext = mimetypes.guess_extension(part.get_content_type())
            if not ext:
                # Use a generic bag-of-bits extension
                ext = '.bin'
            filename = 'part-%03d%s' % (counter, ext)
        counter += 1
        with open(os.path.join(args.directory, filename), 'wb') as fp:
            fp.write(part.get_payload(decode=True))


if __name__ == '__main__':
    main()

در اینجا یک مثال که نحوه ایجاد یک پیام HTML با یک نسخه متنی ساده است را نوشته ایم. برای ایجاد چیزهای کمی جالب تر، ما یک تصویر مربوط به آن را در بخش HTML می نویسیم و یک کپی از آنچه که ما می خواهیم برای ارسال به دیسک داریم، و همچنین ارسال آن را ذخیره کرده ایم...

#!/usr/bin/env python3

import smtplib

from email.message import EmailMessage
from email.headerregistry import Address
from email.utils import make_msgid

# Create the base text message.
msg = EmailMessage()
msg['Subject'] = "Ayons asperges pour le déjeuner"
msg['From'] = Address("Pepé Le Pew", "pepe", "example.com")
msg['To'] = (Address("Penelope Pussycat", "penelope", "example.com"),
             Address("Fabrette Pussycat", "fabrette", "example.com"))
msg.set_content("""\
Salut!

Cela ressemble à un excellent recipie[1] déjeuner.

[1] http://www.yummly.com/recipe/Roasted-Asparagus-Epicurious-203718

--Pepé
""")

# Add the html version.  This converts the message into a multipart/alternative
# container, with the original text message as the first part and the new html
# message as the second part.
asparagus_cid = make_msgid()
msg.add_alternative("""\
<html>
  <head></head>
  <body>
    <p>Salut!</p>
    <p>Cela ressemble à un excellent
        <a href="http://www.yummly.com/recipe/Roasted-Asparagus-Epicurious-203718">
            recipie
        </a> déjeuner.
    </p>
    <img src="cid:{asparagus_cid}" />
  </body>
</html>
""".format(asparagus_cid=asparagus_cid[1:-1]), subtype='html')
# note that we needed to peel the <> off the msgid for use in the html.

# Now add the related image to the html part.
with open("roasted-asparagus.jpg", 'rb') as img:
    msg.get_payload()[1].add_related(img.read(), 'image', 'jpeg',
                                     cid=asparagus_cid)

# Make a local copy of what we are going to send.
with open('outgoing.msg', 'wb') as f:
    f.write(bytes(msg))

# Send the message via local SMTP server.
with smtplib.SMTP('localhost') as s:
    s.send_message(msg)

اگر پیام از آخرین نمونه ای که نوشتم ارسال شد، در اینجا یکی از راه هایی است که می توانیم آن را پردازش کنیم:

import os
import sys
import tempfile
import mimetypes
import webbrowser

# Import the email modules we'll need
from email import policy
from email.parser import BytesParser

# An imaginary module that would make this work and be safe.
from imaginary import magic_html_parser

# In a real program you'd get the filename from the arguments.
with open('outgoing.msg', 'rb') as fp:
    msg = BytesParser(policy=policy.default).parse(fp)

# Now the header items can be accessed as a dictionary, and any non-ASCII will
# be converted to unicode:
print('To:', msg['to'])
print('From:', msg['from'])
print('Subject:', msg['subject'])

# If we want to print a preview of the message content, we can extract whatever
# the least formatted payload is and print the first three lines.  Of course,
# if the message has no plain text part printing the first three lines of html
# is probably useless, but this is just a conceptual example.
simplest = msg.get_body(preferencelist=('plain', 'html'))
print()
print(''.join(simplest.get_content().splitlines(keepends=True)[:3]))

ans = input("View full message?")
if ans.lower()[0] == 'n':
    sys.exit()

# We can extract the richest alternative in order to display it:
richest = msg.get_body()
partfiles = {}
if richest['content-type'].maintype == 'text':
    if richest['content-type'].subtype == 'plain':
        for line in richest.get_content().splitlines():
            print(line)
        sys.exit()
    elif richest['content-type'].subtype == 'html':
        body = richest
    else:
        print("Don't know how to display {}".format(richest.get_content_type()))
        sys.exit()
elif richest['content-type'].content_type == 'multipart/related':
    body = richest.get_body(preferencelist=('html'))
    for part in richest.iter_attachments():
        fn = part.get_filename()
        if fn:
            extension = os.path.splitext(part.get_filename())[1]
        else:
            extension = mimetypes.guess_extension(part.get_content_type())
        with tempfile.NamedTemporaryFile(suffix=extension, delete=False) as f:
            f.write(part.get_content())
            # again strip the <> to go from email form of cid to html form.
            partfiles[part['content-id'][1:-1]] = f.name
else:
    print("Don't know how to display {}".format(richest.get_content_type()))
    sys.exit()
with tempfile.NamedTemporaryFile(mode='w', delete=False) as f:
    # The magic_html_parser has to rewrite the href="cid:...." attributes to
    # point to the filenames in partfiles.  It also has to do a safety-sanitize
    # of the html.  It could be written using html.parser.
    f.write(magic_html_parser(body.get_content(), partfiles))
webbrowser.open(f.name)
os.remove(f.name)
for fn in partfiles.values():
    os.remove(fn)

# Of course, there are lots of email messages that could break this simple
# minded program, but it will handle the most common ones.

خروجی قطعه کد بالا را در ذیل ببینید :

To: Penelope Pussycat <penelope@example.com>, Fabrette Pussycat <fabrette@example.com>
From: Pepé Le Pew <pepe@example.com>
Subject: Ayons asperges pour le déjeuner

Salut!

Cela ressemble à un excellent recipie[1] déjeuner.
۰ نظر موافقین ۰ مخالفین ۰ ۲۴ تیر ۹۸ ، ۱۳:۳۲
سعید دامغانیان