--Python error detection executed from Powershell --As an example, execute the Python function "Convert csv file delimiter to tab delimiter" --The encoding of csv to be read is utf-8.
--use try-except
--Use exception handling except UnicodeDecodeError
to detect deode error in python function
--Receive the above error in Powershell
--Code that calls the function for tab conversion
exeConvertCsvtoTsv.py
from defConvert import CsvToTsv
import sys
#Target file path
path = sys.argv[1]
#Convert from csv to tsv
CsvToTsv(path)
--Tab conversion function
convertTav.py
import csv
import sys
def CsvToTsv(path):
#Array for reading
line = []
try:
#Read ⇒ The encoding of csv to read is utf-8 so an error occurs here
with open(path, "r", newline="", encoding="cp932") as f:
#Create read object (comma separated)
reader = csv.reader(f, delimiter = ",")
#Read
line = [row for row in reader]
#writing
with open(path, "w", newline="", encoding="utf_8") as f:
#Create write object (tab delimited)
writer = csv.writer(f, delimiter = "\t")
#Write all together
writer.writerows(line)
#decode error
except UnicodeDecodeError as err:
print(err)
sys.exit()
finally:
#close
f.close
--Powershell code that executes python functions
main.ps1
#CSV to read
$csv = "test.csv"
try{
#File confirmation
if((Test-Path $out) -eq $false){
$ret = "No File"
Throw $ret
}
#Convert from CSV to TSV
$ret = $null
$ret = python exeConvertCsvtoTsv.py $out #$Receive the execution result on the python side with ret
if($null -ne $ret){
Throw $ret
}
}
catch{
Write-Host "SQL Execution Error`r`n$ret"
}
finally{
Write-Host "end"
}
result
#decode error
SQL Execution Error
'cp932' codec can't decode byte 0x85 in position 7: illegal multibyte sequence
end
--Python is convenient because exception types are prepared for each type of exception.
--except exception type as alias: `` ` --If it is a decode error
UnicodeDecodeError --0 If a division by zero error, `` `ZeroDivisionError` `` --If you do nothing when an exception occurs, you can pass through with `` `pass
Recommended Posts