简体   繁体   中英

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?

PS I am using Python 3.5+

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM