Home > Back-end >  Can I put a variable in my powershell command? (in python)
Can I put a variable in my powershell command? (in python)

Time:01-08

I'm using

    os.system('powershell.exe "Invoke-WebRequest -Uri Link')

And I wounder if you can make link a variable I already defined. My whole code looks like this

import os
link=input("What link do you want? ") 
os.system('powershell.exe "Invoke-WebRequest -Uri link')

But I don't know how (if it's possible) to put a variable in there?

CodePudding user response:

You could simply define a variable that holds the whole string you want to run.

input_var = str(input("Write -> "))
basic_command = "'powershell.exe "   '"Invoke-WebRequest -Uri '
full_command = basic_command   input_var   '"'   "'"
os.system(full_command)

In input_var we convert input into a string. In basic command we set the first part of the command you want to run. In full_command we add the input_var and then we close the whole line with proper " '. And then we run os system with the full command line.

I hope this helps you. I use this concept in lots of scripts

CodePudding user response:

Solution using a formatted string in Python

import os
link = input("What link do you want? ") 
os.system('powershell.exe "Invoke-WebRequest -Uri {link}'.format(link = link))
  •  Tags:  
  • Related