In a sense your argparse works
import argparse import sys print sys.argv parser=argparse.ArgumentParser() parser.add_argument('->') print parser.parse_args('-> test'.split()) print parser.parse_args()
with no arguments, it just assigns None to the > attribute. Note though that you can't access this attribute as args.>. You'd have to use getattr(args,'>') (which is what argparse uses internally). Better yet, assign this argument a proper long name or dest.
1401:~/mypy$ python stack29233375.py ['stack29233375.py'] Namespace(>='test') Namespace(>=None)
But if I give a -> test argument, the shell redirection consumes the >, as shown below:
1405:~/mypy$ python stack29233375.py -> test usage: stack29233375.py [-h] [-> >] stack29233375.py: error: unrecognized arguments: - 1408:~/mypy$ cat test ['stack29233375.py', '-'] Namespace(>='test')
Only the - passes through in argv, and on to the parser. So it complains about unrecognized arguments. An optional positional argument could have consumed this string, resulting in no errors.
Notice that I had to look at the test file to see the rest of the output - because the shell redirected stdout to test. The error message goes to stderr, so it doesn't get redirected.
You can change the prefix char from - (or in addition to it) with an ArgumentParser parameter. But you can't use such a character alone. The flag must be prefix + char (i.e. 2 characters).
Finally, since this argument is required, do you even need a flag? Just make it a positional argument. It's quite common for scripts to take input and/or output file names as positional arguments.
> savefile.samlooks like shell syntax. It makes your command line less intuitive as using it would require using shell syntax escapes.-for options, that's the convention.python script.py > savefile.samthat would be more intuitive. if I can get it to work but only with shell escapes then you are right and then I should settle for-s>is interpreted by the shell, it does not even pass to Python. It redirectsstdoutinto a file. As such, you just need to output tostdout, done.