1

Is there a way I can get this output using the format function

name1 = 'test1'
name2 = 'test2'
ps_script = """powershell.exe Start-Job -ScriptBlock {D:\abc\abc\abc\abc.ps1 {} {} abc}""".format(name1,name2)
print(ps_script)

Output Error :

Traceback (most recent call last): File "main.py", line 6, in ps_script = """powershell.exe Start-Job -ScriptBlock {D:\abc\abc\abc\abc.ps1 {} {} abc}""".format(name1,name2) KeyError: 'D'

Expecting output powershell.exe Start-Job -ScriptBlock {D:\abc\abc\abc\abc.ps1 test1 test2 abc}

Rakesh
  • 81,458
  • 17
  • 76
  • 113
alok tanna
  • 71
  • 6
  • `ps_script = """powershell.exe Start-Job -ScriptBlock {{D:\abc\abc\abc\abc.ps1 {} {} abc}}""".format(name1,name2) `? – Rakesh Apr 23 '19 at 13:52
  • 2
    Don't use string formatting to create a command line. Use a tool that lets you pass a *list* of arguments rather than a single line to be processed by a shell. – chepner Apr 23 '19 at 13:56
  • Possible duplicate of [How can I print literal curly-brace characters in python string and also use .format on it?](https://stackoverflow.com/questions/5466451/how-can-i-print-literal-curly-brace-characters-in-python-string-and-also-use-fo) – Rick Apr 23 '19 at 13:57

3 Answers3

3

You need to escape to get the literal chars:

name1 = 'test1'
name2 = 'test2'
ps_script = """powershell.exe Start-Job -ScriptBlock {{D:\\abc\\abc\\abc\\abc.ps1 {} {} abc}}""".format(name1,name2)
print(ps_script)

OUTPUT:

powershell.exe Start-Job -ScriptBlock {D:\abc\abc\abc\abc.ps1 test1 test2 abc}
DirtyBit
  • 16,613
  • 4
  • 34
  • 55
0

Use double {{ to get the literal {

ps_script = """powershell.exe Start-Job -ScriptBlock {{D:\abc\abc\abc\abc.ps1 {} {} abc}}""".format(name1,name2)
rdas
  • 20,604
  • 6
  • 33
  • 46
0

Instead of creating a string to run a command like this, you may want to consider using subprocess.run() with a list of arguments (as chepner suggested in the comments) instead.

Maybe like this (notice I added an r to make it a raw string; you want to do this when you are entering backslashes so they aren't interpreted as escape characters):

from subprocess import run

cmds_start = r'powershell.exe Start-Job -ScriptBlock {D:\abc\abc\abc\abc.ps1 abc}'.split()
names = 'test1 test2'.split()

cmds = cmds_start[:-1] + names + cmds_start[-1:]

run(cmds)  # use commands list to run, not string

# but can still view the script like:
print(" ".join(cmds))  # or:
print(*cmds, sep=" ")
Rick
  • 43,029
  • 15
  • 76
  • 119