Python Forum

Full Version: add Escape charcters in string
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi
I am trying to call an application from a python script in an Azure Devops pipeline
I build a string to the app path
cmd = "C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\Common7\IDE\CommonExtensions\Microsoft\TestWindow\vstest.console.exe"
The problem is that I need to escape \ with \\ in order to get it run
Have tried
cmd = cmd.replace("\","\\")
but this gives an error SyntaxError: unexpected character after line continuation character
How can I achieve this?
Thanks
Well if you want to play save and have it for every platform you can do this:
import os
path_sep = os.path.sep
then you can create your first path with the system path separators
And two more solutions:
  1. Make it a raw string by prepending "r". In raw strings a backlslash will not be interpreted.
    cmd = r"C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\Common7\IDE\CommonExtensions\Microsoft\TestWindow\vstest.console.exe"
  2. Use forward slashes instead of backslashes. Python will understand this.
Thanks for the replies
I now have the correct string (I think)
But when run as part of an Azure Devops pipeline I get permission denied when calling subprocess?
Here is my code
              programFiles = os.environ['PROGRAMFILES(x86)'] + os.sep
              cmd = '"' + programFiles + 'Microsoft Visual Studio/2019/Professional/Common7/IDE/CommonExtensions/Microsoft/TestWindow/vstest.console.exe' + '"'
              path = Path(cmd)
              print (path)
              subprocess.run([path,
                              filepath,
                              '/Logger:trx;LogFileName=' + fn + '.trx',
                              '/ResultsDirectory:' + resultsFolder
                              ])
Replacing path with a hardcoded string this succeeds - any ideas