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}

3
  • ps_script = """powershell.exe Start-Job -ScriptBlock {{D:\abc\abc\abc\abc.ps1 {} {} abc}}""".format(name1,name2) ? Commented Apr 23, 2019 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. Commented Apr 23, 2019 at 13:56
  • Possible duplicate of How can I print literal curly-brace characters in python string and also use .format on it? Commented Apr 23, 2019 at 13:57

3 Answers 3

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}
Sign up to request clarification or add additional context in comments.

Comments

0

Use double {{ to get the literal {

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

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.