根据PowerShell调用Python脚本并传递PSObject并返回解析后的数据



一些背景:目前我正在使用dbatools从MS SQL服务器向PSObject查询4Mio行(包含50列((每次查询批量10000行(,使用PowerShell处理数据(大量RegEx内容(,并使用SimplySql将数据写回MariaDb。平均而言,我得到大约150行/秒。为了获得这种性能,不得不使用很多技巧(Net的Stringbuilder等(,imho 并没有那么糟糕

作为新的要求,我想检测一些文本单元格的语言,我必须删除个人数据(姓名和地址(。为此,我找到了一些不错的python库(spacy和pycld2(。我用pycld2做了测试——检测效果很好。

用于澄清的简化代码(提示:我是一个python noob(:

#get data from MS SQL
$data = Invoke-DbaQuery -SqlInstance $Connection -Query $Query -As PSObject -QueryTimeout 1800
for ($i=0;$i -lt $data.length;$i++){
#do a lot of other stuff here
#...
#finally make lang detection
if ($LangDetect.IsPresent){
$strLang = $tCaseDescription -replace "([^p{L}p{N}_.s]|`t|`n|`r)+",""
$arg = "import pycld2 as cld2; isReliable, textBytesFound, details = cld2.detect('" + $strLang + "', isPlainText = True, bestEffort = True);print(details[0][1])"
$tCaseLang = & $Env:ProgramfilesPython39python.exe -c $arg
} else {
$tCaseLang = ''
}
}
#write to MariaDB
Invoke-SqlUpdate -ConnectionName $ConnectionName -Query $Query

这个python调用每次都有效,但由于每次循环调用和导入pycld2 lib,它会破坏性能(12行/秒(。因此,这是一个蹩脚的解决方案:(此外,如上所述,我想使用spacy,其中必须解析更多的列以去除个人数据。

我不确定,如果我有心情将整个PS Parser转换为python:|

我相信,一个更好的解决方案可能是将整个PSObject从PowerShell传递到python(在PS循环开始之前(,并在python中处理后返回它和PSObject,但我不知道如何使用python/python函数实现这一点。

你的方法/建议是什么,还有其他想法吗?谢谢:(

以下简化示例向您展示了如何将多个[pscustomobject]([psobject](实例从PowerShell传递到Python脚本(在本例中通过-c作为字符串传递(:

  • 使用JSON作为序列化格式,通过ConvertTo-Json。。。

  • 。。。并通过管道传递该JSON,Python可以通过stdin读取该JSON(标准输入(。

重要

  • 字符编码

    • PowerShell在向外部程序(如Python(发送数据时使用$OutputEncoding首选项变量中指定的编码,这在PowerShell[Core]v6+中默认为无BOM的UTF-8,但在Windows PowerShell中将默认为ASCII(!(。

    • 就像PowerShell限制您向外部程序发送文本一样,它也总是将接收的内容解释为文本,即基于[Console]::OutputEncoding中存储的编码;遗憾的是,截至本文撰写之时,两个PowerShell版本都默认为系统的OEM代码页。

    • 要在两个PowerShell版本中发送和接收(无BOM(UTF-8,请(临时(按如下方式设置$OutputEncoding[Console]::OutputEncoding
      $OutputEncoding = [Console]::OutputEncoding = [System.Text.Utf8Encoding]::new($false)

  • 如果您希望Python脚本也输出对象,请再次考虑使用JSON,您可以在PowerShell上使用ConvertFrom-Json将其解析为对象。

# Sample input objects.
$data = [pscustomobject] @{ one = 1; two = 2 }, [pscustomobject] @{ one = 10; two = 20 }
# Convert to JSON and pipe to Python.
ConvertTo-Json $data | python -c @'
import sys, json
# Parse the JSON passed via stdin into a list of dictionaries.
dicts = json.load(sys.stdin)
# Sample processing: print the 'one' entry of each dict.
for dict in dicts:
print(dict['one'])
'@

如果要传递的数据是单行字符串的集合,则不需要JSON:

$data = 'foo', 'bar', 'baz'
$data | python -c @'
import sys
# Sample processing: print each stdin input line enclosed in [...]
for line in sys.stdin:
print('[' + line.rstrip('rn') + ']')
'@

基于@mktlement0的答案,我想分享完成并测试过的解决方案,将JSON从python返回到Powershell,并考虑正确的字符编码。我已经在一批10万行中尝试过了——没有问题,运行完美且超高速:(

#get data from MS SQL
$query = -join@(
'SELECT `Id`, `CaseSubject`, `CaseDescription`, 
`AccountCountry`, `CaseLang` '
'FROM `db`.`table_global` '
'ORDER BY `Id` DESC, `Id` ASC '
'LIMIT 10000;'
)
$data = Invoke-DbaQuery -SqlInstance $Connection -Query $Query -As PSObject -QueryTimeout 1800
$arg = @'
import pycld2 as cld2
import simplejson as json
import sys, re, logging
def main():
#toggle the logging level to stderr
# https://stackoverflow.com/a/6579522/14226613 -> https://docs.python.org/3/library/logging.html#logging.debug
logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)
logging.info('->Encoding Python: ' + str(sys.stdin.encoding))
# consideration of correct character encoding -> https://stackoverflow.com/a/30107752/14226613
# Parse the JSON passed via stdin into a list of dictionaries -> https://stackoverflow.com/a/65051178/14226613
cases = json.load(sys.stdin, 'utf-8')
# Sample processing: print the 'one' entry of each dict.
# https://regex101.com/r/bymIQS/1
regex = re.compile(r'(?=[^ws]).|[rn]|'|"|\')
# hash table with Country vs Language for 'boosting' the language detection, if pycld2 is not sure
lang_country = {'Albania' : 'ALBANIAN', 'Algeria' : 'ARABIC', 'Argentina' : 'SPANISH', 'Armenia' : 'ARMENIAN', 'Austria' : 'GERMAN', 'Azerbaijan' : 'AZERBAIJANI', 'Bangladesh' : 'BENGALI', 'Belgium' : 'DUTCH', 'Benin' : 'FRENCH', 'Bolivia, Plurinational State of' : 'SPANISH', 'Bosnia and Herzegovina' : 'BOSNIAN', 'Brazil' : 'PORTUGUESE', 'Bulgaria' : 'BULGARIAN', 'Chile' : 'SPANISH', 'China' : 'Chinese', 'Colombia' : 'SPANISH', 'Costa Rica' : 'SPANISH', 'Croatia' : 'CROATIAN', 'Czech Republic' : 'CZECH', 'Denmark' : 'DANISH', 'Ecuador' : 'SPANISH', 'Egypt' : 'ARABIC', 'El Salvador' : 'SPANISH', 'Finland' : 'FINNISH', 'France' : 'FRENCH', 'Germany' : 'GERMAN', 'Greece' : 'GREEK', 'Greenland' : 'GREENLANDIC', 'Hungary' : 'HUNGARIAN', 'Iceland' : 'ICELANDIC', 'India' : 'HINDI', 'Iran' : 'PERSIAN', 'Iraq' : 'ARABIC', 'Ireland' : 'ENGLISH', 'Israel' : 'HEBREW', 'Italy' : 'ITALIAN', 'Japan' : 'Japanese', 'Kosovo' : 'ALBANIAN', 'Kuwait' : 'ARABIC', 'Mexico' : 'SPANISH', 'Monaco' : 'FRENCH', 'Morocco' : 'ARABIC', 'Netherlands' : 'DUTCH', 'New Zealand' : 'ENGLISH', 'Norway' : 'NORWEGIAN', 'Panama' : 'SPANISH', 'Paraguay' : 'SPANISH', 'Peru' : 'SPANISH', 'Poland' : 'POLISH', 'Portugal' : 'PORTUGUESE', 'Qatar' : 'ARABIC', 'Romania' : 'ROMANIAN', 'Russia' : 'RUSSIAN', 'San Marino' : 'ITALIAN', 'Saudi Arabia' : 'ARABIC', 'Serbia' : 'SERBIAN', 'Slovakia' : 'SLOVAK', 'Slovenia' : 'SLOVENIAN', 'South Africa' : 'AFRIKAANS', 'South Korea' : 'Korean', 'Spain' : 'SPANISH', 'Sweden' : 'SWEDISH', 'Switzerland' : 'GERMAN', 'Thailand' : 'THAI', 'Tunisia' : 'ARABIC', 'Turkey' : 'TURKISH', 'Ukraine' : 'UKRAINIAN', 'United Arab Emirates' : 'ARABIC', 'United Kingdom' : 'ENGLISH', 'United States' : 'ENGLISH', 'Uruguay' : 'SPANISH', 'Uzbekistan' : 'UZBEK', 'Venezuela' : 'SPANISH'}
for case in cases:
#concatenate two fiels and clean them a bitfield, so that we not get any faults due line brakes etc.
tCaseDescription = regex.sub('', (case['CaseSubject'] + ' ' + case['CaseDescription']))
tCaseAccCountry = case['AccountCountry']
if tCaseAccCountry in lang_country:
language = lang_country[tCaseAccCountry]
isReliable, textBytesFound, details = cld2.detect(tCaseDescription, 
isPlainText = True, 
bestEffort = True,
hintLanguage = language)
else:
isReliable, textBytesFound, details = cld2.detect(tCaseDescription, 
isPlainText = True, 
bestEffort = True)
#Take Value
case['CaseLang'] = details[0][0]
#logging.info('->Python processing CaseID: ' + str(case['Id']) + ' / Detected Language: ' + str(case['CaseLang']))
#encode to JSON
retVal = json.dumps(cases, 'utf-8')
return retVal
if __name__ == '__main__':
retVal = main()
sys.stdout.write(str(retVal))
'@
$dataJson = ConvertTo-Json $data
$data = ($dataJson | python -X utf8 -c $arg) | ConvertFrom-Json
foreach($case in $data) {
$tCaseSubject = $case.CaseSubject -replace "\", "\" -replace "'", "'"
$tCaseDescription = $case.CaseDescription -replace "\", "\" -replace "'", "'"
$tCaseLang = $case.CaseLang.substring(0,1).toupper() + $case.CaseLang.substring(1).tolower()
$tCaseId = $case.Id

$qUpdate = -join @(
"UPDATE db.table_global SET CaseSubject=`'$tCaseSubject`', "
"CaseDescription=`'$tCaseDescription`', "
"CaseLang=`'$tCaseLang`' "
"WHERE Id=$tCaseId;"
)
try{
$result = Invoke-SqlUpdate -ConnectionName 'maria' -Query $qUpdate
} catch {
Write-Host -Foreground Red -Background Black ("result: " + $result + ' / No. ' + $i)
#break
}
}
Close-SqlConnection -ConnectionName 'maria'

请对语法突出显示的错误表示歉意;脚本块包含SQL、Powershell和Python。。🙄

相关内容

  • 没有找到相关文章

最新更新