5

I'm trying to store the output of powershell in a var:

import subprocess
subprocess.check_call("powershell \"Get-ChildItem -LiteralPath 'HKLM:SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Uninstall' -ErrorAction 'Stop' -ErrorVariable '+ErrorUninstallKeyPath'\"", shell=True, stderr=subprocess.STDOUT)

this way, using check_call, it prints ok, for example:

DisplayName : Skype™

but this way it only prints to screen, so i have to use

import subprocess
output = subprocess.check_output("powershell \"Get-ChildItem -LiteralPath 'HKLM:SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Uninstall' -ErrorAction 'Stop' -ErrorVariable '+ErrorUninstallKeyPath'\"", shell=True, stderr=subprocess.STDOUT)

but then, using check_output, i get:

DisplayName : SkypeT

how can i work around this?

r3v3r53
  • 142
  • 1
  • 1
  • 10

2 Answers2

2

Following this post instructions:How to make Unicode charset in cmd.exe by default?

Its possible to bypass this encoding problem

import subprocess
output = subprocess.check_output("chcp 65001 | powershell \"Get-ChildItem -LiteralPath 'HKLM:SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Uninstall' -ErrorAction 'Stop' -ErrorVariable '+ErrorUninstallKeyPath'\"", shell=True, stderr=subprocess.STDOUT)
r3v3r53
  • 142
  • 1
  • 1
  • 10
1

The output is a of type bytes so you need to either decode it to a string with .decode('utf-8') (or with whatever codec you want), or use str(), Example:

import subprocess
output_bytes = subprocess.check_output("powershell \"Get-ChildItem -LiteralPath 'HKLM:SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Uninstall' -ErrorAction 'Stop' -ErrorVariable '+ErrorUninstallKeyPath'\"", shell=True, stderr=subprocess.STDOUT)

output_string = str(output_bytes)
# alternatively
# output_string = output_bytes.decode('utf-8')

# there are lots of \r\n in the output I encounterd, so you can split
# to get a list
output_list = output_string.split(r'\r\n')

# once you have a list, you can loop thru and print (or whatever you want)
for e in output_list:
    print(e)

The key here is to decode to whatever codec you want to use in order to produce the correct character when printing.

Edwin van Mierlo
  • 2,398
  • 1
  • 10
  • 19
  • Hello, thank you for your reply, but the result was the same... I managed to solve it following this post: [link](https://stackoverflow.com/questions/14109024/how-to-make-unicode-charset-in-cmd-exe-by-default?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa) i'm posting an anwser with the correct code – r3v3r53 Apr 03 '18 at 12:53
  • You can also set `text=True` to obtain results as `str` instead of `bytes`, or `encoding='utf-8'` to set a specific encoding. – shadowtalker Oct 31 '22 at 01:22
  • encoding='ISO-8859-1' worked for me. – FocusedWolf Jul 07 '23 at 18:53