Reputation: 1481
Running into issues executing a PowerShell script from within Python.
The Python itself is simple, but it seems to be passing in \n
when invoked and errors out.
['powershell.exe -ExecutionPolicy Bypass -File', '$Username = "test";\n$Password = "password";\n$URL
This is the code in full:
import os
import subprocess
import urllib2
fetch = urllib2.urlopen('https://raw.githubusercontent.com/test')
script = fetch.read()
command = ['powershell.exe -ExecutionPolicy Bypass -File', script]
print command #<--- this is where I see the \n.
#\n does not appear when I simply 'print script'
So I have two questions:
\n
?$script
?Upvotes: 0
Views: 446
Reputation: 200303
- How do I correctly store the script as a variable without writing to disk while avoiding
\n
?
This question is essentially a duplicate of this one. With your example it would be okay to simply remove the newlines. A safer option would be to replace them with semicolons.
script = fetch.read().replace('\n', ';')
- What is the correct way to invoke PowerShell from within Python so that it would run the script stored in
$script
?
Your command must be passed as an array. Also you cannot run a sequence of PowerShell statements via the -File
parameter. Use -Command
instead:
rc = subprocess.call(['powershell.exe', '-ExecutionPolicy', 'Bypass', '-Command', script])
Upvotes: 2
Reputation: 1
I believe this is happening because you are opening up PowerShell and it is automatically formatting it a specific way.
You could possibly do a for loop that goes through the command output and print without a /n.
Upvotes: 0