Search code examples
python-clickhy

Using `click` in a shell script that has a Hy program in a here document


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.


Solution

  • 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.