Natasha
Natasha

Reputation: 195

Passing arguments to python script in Azure Devops

I am trying to pass a system variable to the python script from azure devops. This is what I currently have in Yaml file:

- script: pytest test/test_pipeline.py 
          --$(global_variable) 
          --junitxml=$(Build.StagingDirectory)/test_pipeline-results.xml
          displayName: 'Testing Pipeline'
          condition: always()

The variable I need in my script is $(global_variable). The variable contains a value of $(Build.SourcesDirectory). It is the global variable. I am getting an error message as "unrecognised arguments" when I run the job.

Any help to tackle this will be helpful.

Thanks!

EDIT:

Complete log:

`##[section]Starting: Testing Pipeline
==============================================================================
Task         : Command line
Description  : Run a command line script using Bash on Linux and macOS and cmd.exe on Windows
Version      : 2.151.2
Author       : Microsoft Corporation
Help         : https://learn.microsoft.com/azure/devops/pipelines/tasks/utility/command-line
==============================================================================
Generating script.
Script contents:
pytest test/test_pipeline.py --my_param="/home/vsts/work/1/s" --junitxml=/home/vsts/work/1/a/test_pipeline-results.xml
========================== Starting Command Output ===========================
[command]/bin/bash --noprofile --norc /home/vsts/work/_temp/64fb4a65-90de-42d5-bfb3-58cc8aa174e3.sh
ERROR: usage: pytest [options] [file_or_dir] [file_or_dir] [...]
pytest: error: unrecognized arguments: --my_param=/home/vsts/work/1/s
  inifile: None
  rootdir: /home/vsts/work/1/s

##[error]Bash exited with code '4'.
##[section]Finishing: Testing Pipeline`

Upvotes: 4

Views: 16905

Answers (1)

Mengdi Liang
Mengdi Liang

Reputation: 18968

I tried to write a simple sample for you refer.

In your .py file, please use add_argument to read in the command line parameter. In this issue, this command line parameter comes from your task specified.

A.py file:

import argparse 

def parse_argument():
       parse = argparse.ArgumentParser(description="ForTest!")
       parse.add_argument("-test_data")
       parse.add_argument("-build_dir")
       

And then, in PythonScript@0 task:

scriptPath: ‘A.py’
argument: -test_data $(myVariable1) -build_dir $(myVariable2)

myVariable1 and myVariable2 are all my customized variable. You can all use environment variable.

Since in python script, add_argument is used to read in the parameter which from command line. So it can receive the value from Argument specified.

In addition, for the issue which in your question, I think you’d better delete the content from your script: --my_param="/home/vsts/work/1/s" and try again. Because --my_param could not the valid argument for pytest.

Hope can help you.

Upvotes: 8

Related Questions