Reputation: 47
I was trying to write a python script like this:
import sys
print sys.argv[1]
print sys.argv[2]
Let's call it arg.py
, and run it in command line:
python arg.py one two
it printed: one two.
Everything was fine.
Then I wanted it to be handy so I put arg.py in my $PATH
and gave it permission to exacuate so wherever I'm I can simply type arg
in command line to run this script. I tried
arg one two
but it failed. The exception said:"bash: test: one: unary operator expected". But if I just do
arg one
it worked fine.
My question is: why I can't pass multiple arguments like this? And what is the right way?
Thanks!
Upvotes: 2
Views: 893
Reputation: 3923
You should parse command line arguments in Python using argparse or the older optparse.
Your script, as it is, should work. Remember to put a shebang line that tells bash to use Python as interpreter, e.g. #! /usr/bin/env python
Upvotes: 0
Reputation: 526543
You probably named your script test
, which is a Bash builtin name. Name it something else.
$ help test
test: test [expr]
Evaluate conditional expression.
Exits with a status of 0 (true) or 1 (false) depending on
the evaluation of EXPR. Expressions may be unary or binary. Unary
expressions are often used to examine the status of a file. There
are string operators and numeric comparison operators as well.
The behavior of test depends on the number of arguments. Read the
bash manual page for the complete specification.
...
That's why you're getting the error from bash
:
bash: test: one: unary operator expected
^--------- because it expects an operator to go before 'two'
^-------- and test doesn't like the argument 'one' you've provided
^-------- because it's interpreting your command as the builtin 'test'
^--- Bash is giving you an error
Upvotes: 4