invo007
invo007

Reputation: 69

python format function with { }

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}

Upvotes: 1

Views: 244

Answers (3)

Rick
Rick

Reputation: 45251

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=" ")

Upvotes: 0

DirtyBit
DirtyBit

Reputation: 16772

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}

Upvotes: 3

rdas
rdas

Reputation: 21275

Use double {{ to get the literal {

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

Upvotes: 0

Related Questions