Passing Python variable to Powershell parameter using Python's Popen
Passing Python variable to Powershell parameter using Python's Popen
I am calling a Powershell script within a Python script using Python's subprocess Popen
. The Powershell script requires two input parameters: -FilePath
and -S3Key
. It uploads a file to AWS S3 server. If I pass in hard coded strings, the script works.
Popen
-FilePath
-S3Key
os.Popen([r'C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe','-ExecutionPolicy','RemoteSigned','./Upload.ps1 -FilePath "C:TEMPtest.txt" -S3Key "mytrialtest/test.txt"'])
os.Popen([r'C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe','-ExecutionPolicy','RemoteSigned','./Upload.ps1 -FilePath "C:TEMPtest.txt" -S3Key "mytrialtest/test.txt"'])
However, if I try to pass in Python string variable, the Powershell script errors out saying it can not find the file specified by the filename variable.
filename = 'C:TEMPtest.txt'
uploadkey = 'mytrialtest/test.txt'
os.Popen([r'C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe','-ExecutionPolicy','RemoteSigned','./Upload.ps1 -FilePath "filename" -S3Key "uploadkey"'])
os.Popen([r'C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe','-ExecutionPolicy','RemoteSigned','./Upload.ps1 -FilePath "filename" -S3Key "uploadkey"'])
Any help would be greatly appreciated. Thanks.
filename = '"' + r"C:TEMPtest.txt" + '"'
uploadkey
I figured out what the issue is. Here is the solution:
– user2896671
Oct 19 '13 at 2:21
Thanks David. Here is a solution I found: filename = "C:TEMPtest.txt" uploadkey = "mytrialtest/test.txt" os.Popen([r'C:WINDOWSsystem32WindowsPowerShellv1.0powershell.exe','-ExecutionPolicy','RemoteSigned','./Upload.ps1 -FilePath ',filename,'-S3Key ',uploadkey])
– user2896671
Oct 19 '13 at 2:29
1 Answer
1
I know, it's an old question, so this is for those who find this question via google:
The solution mentioned in comment has some risks (string injection) and might not work if there are special characters involved. Better:
import subprocess
filename = r'C:TEMPtest.txt'
uploadkey = 'mytrialtest/test.txt'
subprocess.Popen(['powershell',"-ExecutionPolicy","RemoteSigned","-File", './Upload.ps1', '-FilePath:', filename , '-S3Key:', uploadkey])
Notice the :
appended to the parameter names - in most cases it will also work without the :
, but if the value starts with a dash, it will fail.
:
:
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy
Try defining
filename = '"' + r"C:TEMPtest.txt" + '"'
. Do the same thing foruploadkey
.– David
Oct 19 '13 at 0:31