0

How can I convert the following working example of using click with shell + python repl (I think) to hy?

python3 - "$@" <<'EOF'
import click

@click.command()
@click.option('--count', default=1, help='Number of greetings.')
@click.option('--name', prompt='Your name',
              help='The person to greet.')
def hello(count, name):
    """Simple program that greets NAME for a total of COUNT times."""
    for x in range(count):
        click.echo('Hello %s!' % name)

if __name__ == '__main__':
    hello()
EOF

When I use the following hy example with ./test.sh --name shadowrylander --count 3, I get:

Usage: hy [OPTIONS]
Try 'hy --help' for help.

Error: Got unexpected extra argument (-)

when I should be getting:

Hello shadowrylander!
Hello shadowrylander!
Hello shadowrylander!
hy - "$@" <<'EOF'
(import click)

#@(
    (.command click)
    (.option click "--count" :default 1 :help "Number of greetings")
    (.option click "--name" :prompt "Your name" :help "The person to greet.")
    (defn hello
    [count name]
    """Simple program that greets NAME for a total of COUNT times."""
    (for [x (range count)]
        (.echo click "Hello %s" % name)))
)

(if (= __name__ "__main__") (hello))
EOF

Normally I can use hy - "$@" <<'EOF' ... EOF without issue.

Kodiologist
  • 2,984
  • 18
  • 33
ShadowRylander
  • 361
  • 2
  • 8

2 Answers2

1

I don't know enough about click to debug this, but as a Hy developer, I can verify that the error message is produced by click and not by Hy's own command-line-argument processing in hy.cmdline. It would take some digging to figure out whether click or Hy needs to be changed to make this work. My guess is that click is confused by how Hy affects sys.argv or by how Hy partly replaces the Python interpreter.

Your Hy program isn't quite right because it tries to use % as infix. The .echo form needs to be (.echo click (% "Hello %s" name)). With this change, and the Hy code saved to test.hy and run with hy test.hy --name shadowrylander --count 3 (instead of using a shell script as an intermediary), it works as expected.

Kodiologist
  • 2,984
  • 18
  • 33
  • Thanks for the hint; the answer was almost obvious: since hy is a python module, `python3` prepends the `hy` binary path to `argv`; so while `python3` would present `click` with `['-', '--name', 'shadowrylander', '--count', '3']`, `hy` presents `['/home/shadowrylander/.local/bin/hy', '-', '--name', 'shadowrylander', '--count', '3']` instead. Thanks for all the help, again! – ShadowRylander Dec 26 '21 at 19:35
0

My guess is that click is confused by how Hy affects sys.argv or by how Hy partly replaces the Python interpreter.

As per Kodiologist's answer above, the answer is therefore as follows:

(import [sys [argv]])
(del (cut argv 0 1))

This will come right before the click call.

ShadowRylander
  • 361
  • 2
  • 8