pythonautomationazure-pipelinespython-behaverunsettings

Path differs while getting current working directory for local and pipeline


Actually, I've developed a python project using behave framework to automate a solution and pushed it to a repo so that it can be executed using pipeline in agent machine, the paths are getting different for local and pipeline so I want to handle it more generically.

So in order to make the paths generic, in a file config.py I have mentioned the path like this

cwd = os.getcwd()
runsetting_filepath = cwd + r"\resources\UserConfig.runsettings"

Actual path C:\ProgramData\TFS_GIT\python_Automationsuite\DETransitAuto\resources

So when the pipeline is executed the gets downloaded in the agent machine and place in C:\Agent\r110\a\python_Automationsuite\DETransitAuto\resources

the issue is here whenthe code is executed in the local getcwd() returns until DETransitAuto, but when executed in pipeline it returns only until a this causes file not found error in the program, So i need to solution to make these path generic as such it can be handled everywhere


Solution

  • When you run the python script on your local machine, you can execute command under the folder DETransitAuto. So it will get the path until DETransitAuto.

    But when you running the python script on Azure DevOps, it will execute the command under the path: $(System.DefaultWorkingDirectory)(e.g. C:\agent\_work\r1\a) by default. For more detailed info, you can refer to this doc: Classic release and artifacts variables

    To solve this issue, you can set the Working Directory in Azure Pipeline task to let the python script to execute under the correct path.

    For example:

    $(System.DefaultWorkingDirectory)/python_Automationsuite/DETransitAuto

    YAML Sample:

    steps:
    - powershell: |
         python xxx
      workingDirectory: '$(System.DefaultWorkingDirectory)/python_Automationsuite/DETransitAuto'
    

    Classic Sample:

    enter image description here

    In this case, you can get the correct path when executing the python script.

    On the other hand, you can use the following python script to loop all subfolders to find the correct file path:

    import os, sys
    
    rootdir = os.getcwd()
    
    for subdir, dirs, files in os.walk(rootdir):
        for file in files:
            #print os.path.join(subdir, file)
            filepath = subdir + os.sep + file
    
            if filepath.endswith("UserConfig.runsettings"):
                print (filepath)
    

    The filepath variable will show the path of UserConfig.runsettings. It can be a generic path.