LoginSignup
0

More than 3 years have passed since last update.

Powershellから実行したPythonのエラー検知

Posted at

やりたいこと

  • Powershellから実行したPythonのエラー検知
  • 例として「csvファイルの区切り文字をタブ区切りに変換する」Pythonの関数を実行
    • 読み込むcsvのエンコードはutf-8とする

ポイント

  • try-exceptを使う
  • pythonの関数でdeodeエラーを検知する例外処理except UnicodeDecodeErrorを使う
  • Powershellで上記のエラー内容を受け取る

サンプルコード

  • タブ変換用の関数を呼び出すコード
exeConvertCsvtoTsv.py

from defConvert import CsvToTsv
import sys

#対象ファイルパス
path = sys.argv[1]

#csvからtsvへ変換
CsvToTsv(path)   
  • タブ変換用関数
convertTav.py
import csv
import sys
def CsvToTsv(path):

    #読み込み用配列
    line = []
    try:
        #読み込み ⇒ 読み込むcsvのエンコードがutf-8なのでここでエラーが起きる
        with open(path, "r", newline="", encoding="cp932") as f:       
            #読み込みオブジェクト作成(カンマ区切り)
            reader = csv.reader(f, delimiter = ",")
            #読み込み
            line = [row for row in reader]

        #書き込み
        with open(path, "w", newline="", encoding="utf_8") as f:
            #書き込みオブジェクト作成(タブ区切り)
            writer = csv.writer(f, delimiter = "\t")
            #まとめて書き込み
            writer.writerows(line)

    #decodeエラー
    except UnicodeDecodeError as err:
        print(err)
        sys.exit()

    finally:
        #close
        f.close
  • pythonの関数を実行するpowershell側のコード
main.ps1
#読み込むCSV
$csv = "test.csv"

try{ 
    #ファイル確認
    if((Test-Path $out) -eq $false){
        $ret = "No File"
        Throw $ret
    }

    #CSVからTSVへ変換
    $ret = $null
    $ret = python exeConvertCsvtoTsv.py $out #$retでpython側の実行結果を受け取る
    if($null -ne $ret){
        Throw $ret
    }
}
catch{
    Write-Host "SQL Execution Error`r`n$ret"
}
finally{
    Write-Host "end"
}
結果
#decodeエラー
SQL Execution Error
'cp932' codec can't decode byte 0x85 in position 7: illegal multibyte sequence
end
  • Pythonは例外の種類ごとに例外型が用意されていて便利
    • except 例外型 as 別名:
    • decodeエラーならUnicodeDecodeError
    • 0除算エラーならZeroDivisionError
  • 例外発生時に何もしない時はpassでスルーできる

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0