質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.31%
Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

Q&A

解決済

2回答

1174閲覧

Python 関数を使用して冗長なコードを整理したい

asianLad

総合スコア16

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

0グッド

0クリップ

投稿2021/08/25 02:14

似たような処理が続くので関数で整理したいのですが、exceptionの例外処理の文だけを変更したいで、どのように関数に組み込んだら良いのか分からないのでわかる方がいましたらアドバイスしていただけると助かります。
モードの1と2の処理はほとんど同じで最初のプリントの文字とExceptionのエラー後に出力されるプリント文字など主にプリントされる文字のみ使い分けております。どのようにして関数にして1つのコードにできますでしょうか?

以下がコードになります。

Python

1import imapclient, ssl, sys, pprint, imaplib, getpass 2 3from numpy.lib.shape_base import expand_dims 4 5imaplib._MAXLINE = 10000000 6 7 8print("Please choose a number below to conitue") 9print("1. Gmail") 10print("2.Yahoo Japan Mail") 11print('3. For exit') 12 13while_enterd = True 14 15while while_enterd: 16 try: 17 mode = int(input("Number: ")) 18 if mode > 0 and mode < 4: 19 while_enterd = False 20 except Exception as e: 21 print("Please enter valid number") 22 print("Value must be a number between 1 and 3") 23 24context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2) 25 26if mode == 1: 27 print("Gmail is chosen") 28 imap_obj = imapclient.IMAPClient("imap.gmail.com", ssl=True, ssl_context=context) 29 print('Please type your email of Google account that ends with "@gmail.com"') 30 mail_ad = input("email:") 31 print('Please type your App password for gmail') 32 mail_pass = getpass.getpass("App password:") 33 try: 34 imap_obj.login(mail_ad, mail_pass) 35 except Exception as e: 36 print("Error message: " + e) 37 print("If you haven't created App password on your account yet,") 38 print("please refer to https://support.google.com/accounts/answer/185833?hl=en and set App password before you run this programme") 39 exit() 40 print("Logged in successfully") 41 # pprint.pprint(imap_obj.list_folders()) # To return folders of mail in list 42 imap_obj.select_folder("Inbox", readonly=False) 43 print("Please type an email address that you want to delete from your inbox") 44 delete_ad = input("email:") 45 enterd = True 46 while enterd: 47 UIDs = imap_obj.search(["FROM", delete_ad]) 48 number_of_mail = len(UIDs) 49 print("There are " + str(number_of_mail) + " mails. Would you like to delte them all?") 50 answer = input("y/n?:") 51 if answer.lower() == "y": 52 print("Deleting all the mails. This may take for a while...") 53 for delete_id in UIDs: 54 imap_obj.delete_messages(delete_id) 55 else: 56 enterd = False 57 imap_obj.expunge() 58 print("Mails delted successfully") 59 print("Would you like to delete other mails?") 60 answer = input("y/n?:") 61 if answer.lower() == "y": 62 print("Please type an email address that you want to delete from your inbox") 63 delete_ad = input("email:") 64 else: 65 enterd = False 66 imap_obj.logout() 67 print("Logging out from the mail server") 68 exit() 69 70elif mode == 2: 71 print("Yahoo Japan Mail is chosen") 72 imap_obj = imapclient.IMAPClient("imap.mail.yahoo.co.jp", ssl=True, ssl_context=context) 73 print('Please type your email of Yahoo account that ends with "@yahoo.co.jp"') 74 mail_ad = input("email:") 75 print('Please type your password for Yahoo Japan Mail') 76 mail_pass = getpass.getpass("Password:") 77 # Insert Exception later 78 try: 79 imap_obj.login(mail_ad, mail_pass) 80 except Exception: 81 print("Email or Password is not correct. Please try again") 82 exit() 83 print("Logged in successfully") 84 imap_obj.select_folder("Inbox", readonly=False) 85 print("Please type an email address that you want to delete from your inbox") 86 delete_ad = input("email:") 87 enterd = True 88 while enterd: 89 UIDs = imap_obj.search(["FROM", delete_ad]) 90 number_of_mail = len(UIDs) 91 print("There are " + str(number_of_mail) + " mails. Would you like to delte them all?") 92 answer = input("y/n?:") 93 if answer.lower() == "y": 94 print("Deleting all the mails. This may take for a while...") 95 for delete_id in UIDs: 96 imap_obj.delete_messages(delete_id) 97 else: 98 enterd = False 99 imap_obj.expunge() 100 print("Mails delted successfully") 101 print("Would you like to delete other mails?") 102 answer = input("y/n?:") 103 if answer.lower() == "y": 104 print("Please type an email address that you want to delete from your inbox") 105 delete_ad = input("email:") 106 else: 107 enterd = False 108 print("Logging out from the mail server") 109 imap_obj.logout() 110 exit() 111elif mode == 3: 112 print("Exit") 113

よろしくお願いします

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答2

0

ベストアンサー

いろいろな手法があるとは思いますが、基底classを作って継承で作るのが一つの解法かと思います。

python

1class base_cls(object): 2 def imap_access(self): 3 self.imap_obj = imapclient.IMAPClient("imap.mail.yahoo.co.jp", ssl=True, ssl_context=context) 4 print('Please type your email of Yahoo account that ends with "@yahoo.co.jp"') 5 self.mail_ad = input("email:") 6 print('Please type your password for Yahoo Japan Mail') 7 self.mail_pass = getpass.getpass("Password:") 8 9class gmail_access(base_cls): 10 def __init__(self) -> None: 11 print("Gmail is chosen") 12 super().__init__() 13 14 def imap_login(self): 15 self.imap_access() 16 try: 17 self.imap_obj.login(self.mail_ad, self.mail_pass) 18 except Exception as e: 19 print("Error message: " + e) 20#以下省略 21 22class yahoo_access(base_cls): 23 print("Yahoo Japan Mail is chosen") 24 super().__init__() 25 26 def imap_login(self): 27 self.imap_access() 28 try: 29 self.imap_obj.login(self.mail_ad, self.mail_pass) 30 except Exception as e: 31 print("Email or Password is not correct. Please try again") 32#以下省略

動作確認はしていませんが、上記のような感じで書けるかと思います。

投稿2021/08/25 02:50

TANAKAKazuyoshi

総合スコア96

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

ppaul

2021/08/25 02:58

やることが二つだけなら、クラスを一つ作って、インスタンスを作る時にパラメータを与え、GmailインスタンスとYahooインスタンスの二つを作る方が良いのでは、と思います。
asianLad

2021/08/25 03:27

```python import imapclient, ssl, sys, pprint, imaplib, getpass from numpy.lib.shape_base import expand_dims imaplib._MAXLINE = 10000000 print("Please choose a number below to conitue") print("1. Gmail") print("2.Yahoo Japan Mail") print('3. For exit') while_enterd = True while while_enterd: try: mode = int(input("Number: ")) if mode > 0 and mode < 4: while_enterd = False except Exception as e: print("Please enter valid number") print("Value must be a number between 1 and 3") context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2) def mail_delete(mail_server): print( mail_server + " is chosen") imap_obj = imapclient.IMAPClient("imap.gmail.com", ssl=True, ssl_context=context) print('Please type your email of ' + mail_server + ' account that ends with ' +domain) mail_ad = input("email:") print('Please type your password for ' + mail_server) mail_pass = getpass.getpass("Password:") try: imap_obj.login(mail_ad, mail_pass) except Exception as e: # print("Error message: " + e) print(exception_message) exit() print("Logged in successfully") # pprint.pprint(imap_obj.list_folders()) # To return folders of mail in list imap_obj.select_folder("Inbox", readonly=False) print("Please type an email address that you want to delete from your inbox") delete_ad = input("email:") enterd = True while enterd: UIDs = imap_obj.search(["FROM", delete_ad]) number_of_mail = len(UIDs) print("There are " + str(number_of_mail) + " mails. Would you like to delte them all?") answer = input("y/n?:") if answer.lower() == "y": print("Deleting all the mails. This may take for a while...") for delete_id in UIDs: imap_obj.delete_messages(delete_id) else: enterd = False imap_obj.expunge() print("Mails delted successfully") print("Would you like to delete other mails?") answer = input("y/n?:") if answer.lower() == "y": print("Please type an email address that you want to delete from your inbox") delete_ad = input("email:") else: enterd = False imap_obj.logout() print("Logging out from the mail server") exit() if mode == 1: domain = '"@gmail.com"' exception_message = ("If you haven't created App password on your account yet, \n please refer to https://support.google.com/accounts/answer/185833?hl=en and set App password before you run this programme") mail_delete("Gmail") elif mode == 2: domain = '"@gmail.com"' exception_message = ("Email or passowrod is not correct. Please try again") mail_delete("Yahoo Japan Mail") elif mode == 3: print("Exit") ``` できました。ありがとうございます。
guest

0

単に、異なる部分は引数にして、呼び出し時に指定すれば良いんじゃ無いでしょうか。

投稿2021/08/25 02:41

otn

総合スコア86301

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.31%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問