Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing python command line arguments using bazel py_binary

So I am trying to combine using python and bazel together and I was wondering if there is a way to pass the values of a python script arguments while running that script through a bazel target.

So the idea is:

I have some main.py file that accepts args and executes some logic

#main.py
import argparse

class ClassA:
  def __init__(self, arg1):
    pass
  #incredible logic happens here :D 


def parse_arguments():
    parser = argparse.ArgumentParser(description="....")
    parser.add_argument(
        "--arg1",
        required=True)

if __name__ == "__main__":
    ARGS = parse_arguments()
    ClassA(ARGS.arg1) # will execute whatever has to happen and return something

usually, in order to run this script, I would just run something like:

python -m main.py --arg1=val1

but now I am interested in executing this script while having a bazel target for it, something like:

#BUILD 

py_binary( 
    name = "binary1",
    srcs = ["main.py"],
    main = "main.py",
    visibility = ["//public"],
)

Is there a way to run that script using somethin like: bazel run //path/to/py_binary --arg1=val1

If not what are the alternatives on running that python script while using this bazel target?

P.S. I am using Python 3.5+

like image 810
Alex Avatar asked Jun 15 '26 17:06

Alex


1 Answers

You can do this by putting -- before the command line options you want to pass to the binary, like this:

bazel run //pkg:binary1 -- --arg1=val1

or

bazel run -- //pkg:binary1 --arg1=val1

See https://docs.bazel.build/versions/master/user-manual.html#run

like image 137
ahumesky Avatar answered Jun 18 '26 07:06

ahumesky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!