0

I'm having a problem with sending a JSON variable from PowerShell to python.

That's the code I have for python:

import subprocess
import os 
import json

firstname = 'FirstName'
lastname = 'LastName'

args2 = '-FIRSTNAME %s -LASTNAME %s' % (firstname, lastname)

test = subprocess.run([
    'powershell.exe',
    'Path\\Test2.ps1',
    args2,
])

jsonvalue = json.loads(test)

print(jsonvalue)

And here's for PowerShell:

Param(
    [Parameter(Mandatory)][string]$FIRSTNAME,
    [Parameter(Mandatory)][string]$LASTNAME
)

$result = [PSCustomObject]@{
    FirstName = $FIRSTNAME
    LastName = $LASTNAME
    FullName = $FIRSTNAME + " " + $LASTNAME
}

return $result | ConvertTo-Json

JSON output:

{
    "FirstName":  "FirstName",
    "LastName":  "LastName",
    "FullName":  "FirstName LastName"
}

The error message I'm getting is:

TypeError: the JSON object must be str, bytes or bytearray, not CompletedProcess

From what I've read it looks like subprocess.run is returning CompletedProcess variable type. Unfortunately, although I tried to bypass it wouldn't work.

I think it might be pretty simple, but I cannot find an answer on my own. I'm pretty new to Python and connecting those two languages might be a bit of overkill for a beginner but isn't that the best way to learn? :D

3
  • Shouldn't -FIRSTNAME, firstname, etc all be separate elements of run's list argument, rather than combined in a single string value? Commented Jul 20, 2021 at 13:39
  • 1
    arg2 = ['-FIRSTNAME', firstname, '-LASTNAME', lastname]; run(['powershell.exe', 'PATH...', *args2])? Commented Jul 20, 2021 at 13:40
  • I tried to do it that way at the beginning, but it wouldn't work. EDIT: Oh, I see, there's an asterisk before "args", now it works. Commented Jul 20, 2021 at 14:17

1 Answer 1

2

run doesn't return a string containing the output; you want the stdout attribute of the return value.

test = subprocess.run(...)
jsonvalue = json.loads(test.stdout)

Or, use the check_output function instead.

test = subprocess.check_output(...)
jsonvalue = json.loads(test)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.