这个Powershell命令的python版本是什么?



希望将powershell代码转换为python:

$secretArgs = @{
    fileName = "test.pem"
    fileAttachment = [IO.File]::ReadAllBytes("C:brian13568-test.txt")
} | ConvertTo-Json

*更新:我正在尝试此代码以获得类似的结果:

import json
test_file = open("test.txt", "rb")
test_file_name = "test.txt"
body = {"filename":test_file_name,"fileattachment":test_file}
print(body)
data = json.dumps(body)
print(data)

为这个powershell代码片段找到一个python方法的目标:

    $endpoint ="$destinationapi/secrets/$fileSecretId/fields/$fileFieldToUpdate"
    echo $endpoint
    
    $secretArgs = @{
        fileName = "test.pem"
        fileAttachment = [IO.File]::ReadAllBytes("C:brian13568-test.txt")
    } | ConvertTo-Json
    
    $response = $null
    $response = Invoke-RestMethod -Method Put -Uri $endpoint -Headers $destinationheaders -Body $secretArgs -ContentType "application/json"
import json
secretArgs = {"fileName": "test.pem"}
with open("test.pem", "r") as f:
    data = f.read()
raw_bytes = list(bytearray(data, "utf-8"))
secretArgs["fileAttachment"] = list(bytes(raw_bytes))
print(json.dumps(secretArgs))

我创建了一个小的测试文件来看看powershell命令到底做了什么。

PS C:> cat C:temp13568-test.txt
blah blah blah
PS C:> $secretArgs = @{
>>     fileName = "test.pem"
>>     fileAttachment = [IO.File]::ReadAllBytes("C:/temp/13568-test.txt")
>> } | ConvertTo-Json
PS C:> echo $secretArgs
{
    "fileName":  "test.pem",
    "fileAttachment":  [
                           98,
                           108,
                           97,
                           104,
                           32,
                           98,
                           108,
                           97,
                           104,
                           32,
                           98,
                           108,
                           97,
                           104
                       ]
}
PS C:>

要在Python中复制它似乎是:

import json
from pathlib import Path
test_file = Path("C:/temp/13568-test.txt")
content = {"fileName": "test.pem",
           "fileAttachment": list(test_file.read_bytes())}
secret_args = json.dumps(content, indent=4)
print(secret_args)

输出如下:

{
    "fileName": "test.pem",
    "fileAttachment": [
        98,
        108,
        97,
        104,
        32,
        98,
        108,
        97,
        104,
        32,
        98,
        108,
        97,
        104
    ]
}

最新更新