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

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

新規登録して質問してみよう
ただいま回答率
85.48%
Visual Studio

Microsoft Visual StudioはMicrosoftによる統合開発環境(IDE)です。多種多様なプログラミング言語に対応しています。

Python

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

Q&A

解決済

2回答

822閲覧

python 3.7 でwithを使用した際にエラーが発生する

bg_t

総合スコア1

Visual Studio

Microsoft Visual StudioはMicrosoftによる統合開発環境(IDE)です。多種多様なプログラミング言語に対応しています。

Python

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

0グッド

1クリップ

投稿2020/10/17 04:40

編集2020/10/17 05:32

win10 VS2019でpython3.7(64bit)を利用してプログラムを書いているのですが、プログラム内で with を使用するとプログラム終了時にコンソールにエラーが表示されます

python

1# ココ 2f = open() 3f.close()

形式にするとエラーが表示されなくなるのですが、これ以上の原因が究明できないので教えて頂けると嬉しいです

python

1import os 2import pandas as pd 3from tqdm import tqdm 4import re # 文字列編集 5import time 6import lib 7 8try: 9 import google.colab 10 IN_COLAB = True 11except: 12 IN_COLAB = False 13 14if IN_COLAB: # Google Colabで実行している場合 15 CSV_PATH = "/content/rakuten_product_data.csv" 16 URL_LIST_PATH = "./image_url.lst" 17 IMAGE_URL_CSV_PATH = "./delete_image_name.csv" 18 R_CABINET_FORMAT_PATH = "./r_cabinet_delete_format.txt" 19 URL_INFO_TEXT_PATH = "./image_url.txt" 20else: # ローカルで実行している場合 21 CSV_PATH = "./rakuten_product_data.csv" 22 URL_LIST_PATH = "./image_url.lst" 23 IMAGE_URL_CSV_PATH = "./delete_image_name.csv" 24 R_CABINET_FORMAT_PATH = "./r_cabinet_delete_format.txt" 25 URL_INFO_TEXT_PATH = "./image_url.txt" 26VERSION = "1.0.0" 27STOCK = 0 # 在庫あり 28NO_STOCK = 1 # 在庫なし 29LOCAL_IMG_DIR = "./image" 30RAKUTEN_FORMAT_DELETE_PATH = "" # RMSフォーマット用に画像URLから削除する部分 31IMAGE_URL_CSV_COLUMNS = ["file_name", "url", "deleted", "error"] 32 33 34 35if os.path.isfile(CSV_PATH): 36 load_csv = pd.read_csv(CSV_PATH, encoding="cp932") 37else: 38 exit() 39 40stock_or = [load_csv[load_csv["在庫数"] == 1], load_csv[load_csv["在庫数"] == 0]] # 在庫がある商品とない商品のリスト 41all_num = len(load_csv) # 商品の数 42stock_num = len(stock_or[STOCK]) # 在庫あり商品の数 43 44img_num_no_stock = 0 # 在庫がない商品に含まれる画像の数 45img_num_stock = 0 # 在庫がある商品に含まれる画像の数 46not_top_img_num = 0 # サムネを含まない、在庫がない商品に含まれる画像の数 47no_img_item_num = 0 # 画像が無い商品の数 48i = 0 49 50for row_stock_or in stock_or: 51 for row in row_stock_or["商品画像URL"]: 52 if type(row) == str and len(row.split()) != 0: # URL情報が格納されていれば 53 if i == STOCK: # 在庫がある場合 54 img_num_stock += len(row.split()) 55 else: # 在庫がない場合 56 img_num_no_stock += len(row.split()) 57 not_top_img_num += len(row.split()) - 1 58 else: 59 no_img_item_num += 1 60 i += 1 61 62 63#中略 64 65 66item_numbers = list(stock_or[NO_STOCK]["商品管理番号(商品URL)"]) 67item_names = list(stock_or[NO_STOCK]["商品名"]) 68img_urls = list(stock_or[NO_STOCK]["商品画像URL"]) 69img_urls_stock = list(stock_or[STOCK]["商品画像URL"]) 70 71#中略 72 73 74print("\n削除画像一覧をテキストに出力しますか? (y/n)") 75in_str = input() 76if in_str == "y": 77 output_data = [] # CSVとして出力するためのデータ 78 for i in range(len(img_urls)): 79 if type(img_urls[i]) == str: # URLが含まれない商品をスキップする 80 images = img_urls[i].split(" ") # 一つの商品に含まれるURLのリスト 81 for j in range(1, len(images)): # サムネの画像をスキップする 82 output_data.append([os.path.basename(images[j]), images[j], False]) 83 84 image_name_list_stock = [] # 在庫がある商品の写真のリスト 85 for i in range(len(img_urls_stock)): 86 if type(img_urls_stock[i]) == str: # URLが含まれない商品をスキップする 87 images = img_urls_stock[i].split(" ") # 一つの商品に含まれるURLのリスト 88 for j in range(1, len(images)): # サムネの画像をスキップする 89 image_name_list_stock.append(os.path.basename(images[j])) 90 91 print("画像情報を精査します") 92 exclusion_image_list = [] # 削除する画像リストから取り除く画像 93 image_name_list = [row[0] for row in output_data] # 在庫がない商品の写真のリスト 94 for row in tqdm(image_name_list): 95 for row2 in image_name_list_stock: 96 if row == row2: 97 exclusion_image_list.append(row) 98 exclusion_image_list = set(exclusion_image_list) # 万が一同じ画像があれば取り除く 99 if len(exclusion_image_list) == 0: 100 print("\n問題は見つかりませんでした") 101 else: 102 print("\n" + str(len(exclusion_image_list)) + " 件の販売中商品への再利用画像が見つかりました") 103 print(exclusion_image_list) 104 105 for row in output_data: 106 row.append(False) # 4 列目を追加する 107 for row2 in exclusion_image_list: 108 if row[0] == row2: 109 row[3] = True # 4 列目を書き換える 110 111 list_len = len(image_name_list) # リストの大きさ 112 unique_list_len = len(set(image_name_list)) # 一意に変換したリストの大きさ 113 if list_len != unique_list_len: 114 print("\n警告 : 同名の画像が存在します " + str(list_len-unique_list_len) + " / " + str(unique_list_len)) 115 print([x for x in dict.fromkeys(image_name_list) if image_name_list.count(x) > 1]) 116 csv_df = pd.DataFrame(output_data, columns=IMAGE_URL_CSV_COLUMNS) 117 csv_df.to_csv(IMAGE_URL_CSV_PATH, index=False) 118 print("\n削除すべき画像の情報をCSV形式で出力しました") 119 120 121 if os.path.isfile(IMAGE_URL_CSV_PATH): 122 load_img_csv = pd.read_csv(IMAGE_URL_CSV_PATH, encoding="cp932") 123 else: 124 lib.print_error_log("削除画像一覧ファイルが見つかりませんでした") 125 exit() 126 127 with open(R_CABINET_FORMAT_PATH, mode="w") as f: # ココ 128 for i in range(len(load_img_csv[IMAGE_URL_CSV_COLUMNS[0]])): 129 if not load_img_csv["error"][i]: 130 f.write(load_img_csv["url"][i].replace(RAKUTEN_FORMAT_DELETE_PATH, "") + "\n") # 指定のフォーマットに変換して出力する 131 132 133lib.program_pause()

lib.py↓

python

1import os 2import time 3import datetime 4import urllib.error # urlを扱うモジュール 5import urllib.request 6import inspect # 活動中のオブジェクトの情報を取得する 7 8__version__ = "1.0.0" 9 10# ログを出力する 11def print_log(message, console_print = True, error_frame = None): 12 LOG_PATH = "./lib.log" 13 if error_frame != None: # エラーログの場合はファイルを変更する 14 LOG_PATH = "./error.log" 15 if console_print: 16 print(message) 17 18 time_now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") # 現在時刻を取得する 19 if not os.path.isfile(LOG_PATH) or os.path.getsize(LOG_PATH) < 1024*1000*10: # 10MBより小さければ出力する 20 with open(LOG_PATH, mode="a") as f: 21 if error_frame != None: # エラーログ 22 f.write("[{}] {}({})".format(time_now, error_frame.f_code.co_name, error_frame.f_lineno).ljust(60) + message + "\n") 23 else: # 普通のログ 24 f.write("[{}] {}\n".format(time_now, message)) 25 return True 26 else: 27 print("ログファイルの容量がいっぱいの為、出力を中止しました") 28 return False 29 30# エラーログを出力する 31def print_error_log(message, console_print = True): 32 frame = inspect.currentframe().f_back # 関数が呼ばれた場所の情報を取得する 33 return print_log(message, console_print, frame) 34 35# インターネット上からファイルをダウンロードする関数 36def download_file(url, dst_path): 37 try: 38 with urllib.request.urlopen(url) as web_file: 39 data = web_file.read() 40 with open(dst_path, mode='wb') as local_file: 41 local_file.write(data) 42 time.sleep(0.1) 43 return True 44 except urllib.error.URLError as e: 45 print_error_log(e) 46 return False 47 48# ファイルをダウンロードして、失敗時に再ダウンロードを試みる関数 49def download_and_check_file(url, dst_path): 50 TRIAL_NUM = 300 # 失敗時の試行回数 51 TRIAL_INTERVAL = 5 # 再ダウンロード時のクールタイム 52 download_file(url, dst_path) 53 for i in range(TRIAL_NUM): 54 if not os.path.isfile(dst_path): 55 print_error_log("ダウンロードに失敗しました、" + str(TRIAL_INTERVAL) + "秒後に再ダウンロードします ( " + str(i + 1) + " Fail )") 56 time.sleep(TRIAL_INTERVAL) 57 download_file(url, dst_path) 58 else: # ダウンロード成功 59 return True 60 return False 61 62# プログラム終了時に一時停止する関数 63def program_pause(program_end = True): 64 if not __debug__: # デバッグでなければ一時停止する 65 if program_end: 66 message = "Press Enter key to exit . . ." 67 else: 68 message = "Press Enter key to continue . . ." 69 input(message) 70 return True

Traceback (most recent call last):
File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\runpy.py", line 193, in _run_module_as_main
"main", mod_spec)
File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\runpy.py", line 85, in run_code
exec(code, run_globals)
File "c:\program files (x86)\microsoft visual studio\2019\community\common7\ide\extensions\microsoft\python\core\debugpy_main
.py", line 45, in <module>
cli.main()
File "c:\program files (x86)\microsoft visual studio\2019\community\common7\ide\extensions\microsoft\python\core\debugpy/..\debugpy\server\cli.py", line 430, in main
run()
File "c:\program files (x86)\microsoft visual studio\2019\community\common7\ide\extensions\microsoft\python\core\debugpy/..\debugpy\server\cli.py", line 267, in run_file
runpy.run_path(options.target, run_name=compat.force_str("main"))
File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\runpy.py", line 263, in run_path
pkg_name=pkg_name, script_name=fname)
File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\runpy.py", line 96, in _run_module_code
mod_name, mod_spec, pkg_name, script_name)
File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\runpy.py", line 85, in _run_code
exec(code, run_globals)
File "C:\Users\media\source\repos\rakuten_rms_manager\rakuten_rms_manager\rakuten_rms_manager.py", line 174, in <module>
'''
File "c:\program files (x86)\microsoft visual studio\2019\community\common7\ide\extensions\microsoft\python\core\debugpy_vendored\pydevd_pydevd_bundle\pydevd_frame.py", line 179, in trace_exception
if is_unhandled_exception(container_obj, self._args[0], frame, exc_info[1], exc_info[2]) and
File "c:\program files (x86)\microsoft visual studio\2019\community\common7\ide\extensions\microsoft\python\core\debugpy_vendored\pydevd_pydevd_bundle\pydevd_frame.py", line 66, in is_unhandled_exception
container_obj.try_except_infos = try_except_infos = py_db.collect_try_except_info(frame.f_code)
File "c:\program files (x86)\microsoft visual studio\2019\community\common7\ide\extensions\microsoft\python\core\debugpy_vendored\pydevd_pydevd_bundle\pydevd_collect_bytecode_info.py", line 216, in collect_try_except_info
stack_in_setup[-1].except_end_bytecode_offset = instruction.offset
IndexError: list index out of range

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

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

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

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

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

otn

2020/10/17 04:57

ifの中は実行されないので、勘違いでは?
bg_t

2020/10/17 05:09

実際にエラーが発生するプログラムでif 内の条件を書き換えてFALSEするとエラーが発生しませんでした しかし、そのifのネスト内には問題のエラーの場所に入るまでに複数のprint()が含まれており、これらは一切出力されていません with openではなく、条件分岐とその直後のあたりを再度確認してみます
guest

回答2

0

Tracebackで出力されているエラーの原因はこのコード内にありません。
貼れない原因が直接書いたトークンなどの個人情報であれば、そこだけを伏せてなるべく問題のコード全体を貼っていただかないと回答のしようがないです。
追記依頼を出そうと思いましたが、

プログラム全体を貼ることが出来ないので、これらの情報で原因が推測できる方がいらっしゃいましたら教えて頂けると幸いです。

とのことですので、文字通り推測しかできませんが

IndexError: list index out of range

と出ているのを見ると、リストの要素数を超える要素を参照しているとは推測できます
例えば、

l = [1,2,3,4,5,6,7,8] l[10]

上記の例では8つしか要素のないリストオブジェクトの10番目を取得しようとしているので、IndexErrorを吐きます。
また、リストが空であればどう取得してもIndexErrorになります。
リストから要素を取得している処理の周辺を見てみると絞れると思います。
残念ながらこれ以上のことは判断しかねます。

投稿2020/10/17 05:16

nashiroaoi

総合スコア24

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

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

bg_t

2020/10/17 05:21

コメントアウトした部分がindexと一切関係なかったので、個人情報を伏せたものを用意します
guest

0

ベストアンサー

input関数を使用しないようにすればエラーは消えると思います。
それ以外の解決法は分かりません。

投稿2020/10/30 01:27

nicoyou

総合スコア129

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

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

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.48%

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

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

質問する

関連した質問