Вот как выглядит строка Write-Output из Powershell через subprocess.Popen () выглядит так:
Вот что Write- Выходная строка из Powershell через подпроцесс. Open () выглядит как raw:
Вот мой желаемый результат:
Вот мой код:
# 5 Exceute powershell script from the command line
#universal_newlines=True makes it so that data is piped as text not as bytes
process = subprocess.Popen(["powershell.exe",file_path], stdout=subprocess.PIPE, stderr = subprocess.STDOUT, shell = True, universal_newlines=True)
# 6 access output from the command line
powershell_communication = process.communicate()[0]
# 7 return the string output as a list, split by new lines with blank values filtered out
credentials_list = list(filter(None,powershell_communication.split('\n')))
#8 replace single space (first occurrence only) with underscore to protect the field names in the upcoming split
protect_credential_field_names = []
for i in credentials_list:
protect_credential_field_names.append( i.replace(' ','_',1))
#9 create dictionary of credential field names and value in prep for transformation to dataframe
keys = []
values = []
#starting at index value two to exclude name/value and ---- returns from the command line
for i in range(2,len( protect_credential_field_names)):
#split key value pairs into two separate list elements (ensured by maxsplit = 1) where there is a space
key_values_list = protect_credential_field_names[i].split(' ',maxsplit = 1)
#exclude fields with empty values
if len(key_values_list) > 1:
#append field names to the keys list
keys.append(key_values_list[0])
#append values to the values list and remove trailing and leading spaces yo
values.append(key_values_list[1].strip())
#10 return key and value lists as dictionary in prep for final transformation to dataframe
clean_keys = []
#10.1 areplace underscores with spaces and if applicable,remove resulting trainling and leading spaces
for i in keys:
clean_key = i.replace('_',' ')
clean_keys.append(clean_key.strip())
#10.2 create dictionary from the clean keys list and the values list
credentials_dictionary = dict(zip(clean_keys,values))
#11 return dictionary inside of a list (this [] resolves scalar value index issue) so you can turn the dictionary into a dataframe
credentials_df = pd.DataFrame.from_dict([credentials_dictionary])
#12 delete temporary powershellscript file
os.remove(file_path)