Python, optparse and file mask

if __name__=='__main__':
    parser = OptionParser()
    parser.add_option("-i", "--input_file", 
                      help="Read input from FILE", metavar="FILE")

    (options, args) = parser.parse_args()
    print options

result is

$ python -i video_*
{'input_filename': 'video_1.wmv'}

there are video_[1-6].wmv in the current folder. Question is why video_* become video_1.wmv. What i'm doing wrong?

Asked by: Michelle682 | Posted: 28-01-2022

Answer 1

Python has nothing to do with this -- it's the shell.


$ python -i 'video_*'

and it will pass in that wildcard.

The other six values were passed in as args, not attached to the -i, exactly as if you'd run python -i video_1 video_2 video_3 video_4 video_5 video_6, and the -i only attaches to the immediate next parameter.

That said, your best bet might to be just read your input filenames from args, rather than using options.input.

Answered by: Agata161 | Posted: 01-03-2022

Answer 2

Print out args and you'll see where the other files are going...

They are being converted to separate arguments in argv, and optparse only takes the first one as the value for the input_filename option.

Answered by: Kevin203 | Posted: 01-03-2022

Answer 3

To clarify:

aprogram -e *.wmv

on a Linux shell, all wildcards (*.wmv) are expanded by the shell. So aprogram actually recieves the arguments:

sys.argv == ['aprogram', '-e', '1.wmv', '2.wmv', '3.wmv']

Like Charles said, you can quote the argument to get it to pass in literally:

aprogram -e "*.wmv"

This will pass in:

sys.argv == ['aprogram', '-e', '*.wmv']

Answered by: Emily957 | Posted: 01-03-2022

Answer 4

It isn't obvious, even if you read some of the standards (like this or this).

The args part of a command line are -- almost universally -- the input files.

There are only very rare odd-ball cases where an input file is specified as an option. It does happen, but it's very rare.

Also, the output files are never named as args. They almost always are provided as named options.

The idea is that

  1. Most programs can (and should) read from stdin. The command-line argument of - is a code for "stdin". If no arguments are given, stdin is the fallback plan.

  2. If your program opens any files, it may as well open an unlimited number of files specified on the command line. The shell facilitates this by expanding wild-cards for you. [Windows doesn't do this for you, however.]

  3. You program should never overwrite a file without an explicit command-line options, like '-o somefile' to write to a file.

Note that cp, mv, rm are the big examples of programs that don't follow these standards.

Answered by: Rafael586 | Posted: 01-03-2022

Similar questions

Python Optparse list

I'm using the python optparse module in my program, and I'm having trouble finding an easy way to parse an option that contains a list of values. For example: --groups one,two,three. I'd like to be able to access these values in a list format as options.groups[]. Is there an optparse option to convert comma separated values into a list? Or do I have to do this manuall...

python - Ignore optparse if value is given

I would like to have the ability to pass an argument w/o having to specify an option for optparse. If I do pass an option, it has to be a known option or else the script will fail. Rsync the following file to destination filename Rsync the following folder to destination (all this is figured out in function I create). -f foldername

Python optparse is not able to parse the `$` symbol

if I am using a $ symbol in the arguments, python optparse is not able to parse it properly. It just ignores the symbol and the next character. If I am giving a \ before $ then it is working fine. But I don't want to give a \. Please help me out how to overcome this situation. Its happening only in Linux; on Windows it is working fine. Thanks ...

Python 3 - optparse - how to change return value when error occurs

I have o problem with return value of optparse. When script find an unknown argument it exites with error message and return value 2 (echo $?). I need to have 1 returned and also I want to set my own error mesage, how can I do that? Here is a part of code: import sys import re import ast from optparse import OptionParser parser = OptionParser(usage="usage: %prog [OPTIONS] ", version="%prog...

Python optparse - option not being read as false

I am relatively new to Python and playing with optparse. I have the parser function as such: def parse(argv): """Option parser, returns the options leave the args.""" version = '0.1' usage = 'Usage: %prog [options] -f|--file <FILENAME>' parser = optparse.OptionParser(usage=usage,version="%prog: v.{}".format(version)) parser.add_option("-m", "--mock", action="store_tr...

python - what is the best way to parse, cant use optparse

Closed. This question is opinion-based. It is not c...

python - Why do I still have optparse being used in Django v1.7.4?

argparse is the tool Django (allegedly) uses for parsing the command line, as per this commit and this support ticket. However, nine months have passed now, and when I visit the BaseCommand declaration I see:

python optparse get specified number of args after an option

./hello_world -c arg1 arg2 arg3 Is it possible to code so that option -c would only get two arguments (arg1 and arg2)? parser.add_option("-c", action="append2", <--- maybe something like that? dest="verbose", help="make lots of noise [default]")

scope - Python optparse from method call?

I have two python scripts with the following structure: # from optparse import OptionParser def main(): parser = OptionParser() parser.add_option("-a", "--add-foobar", action="store_true", help="set foobar true", dest="foobar", default=False) options, args = parser.parse_args() print options.foobar if __name__ == "__main__": main() # from Script1 import ma...

python optparse how to set a args of list?

I want to pass data to script, like this if __name__ == '__main__': usage = 'python [-h <host>][-p <port>][-r <risk>]arg1[,arg2..]' parser = OptionParser(usage) parser.add_option('-o', '--host', dest='host', default='', ┊ help='mongodb host') parser.add_option('-p', '--port', dest='port', default=27017, ┊ help="mongodb port") parser.add_op...

Python Optparse list

I'm using the python optparse module in my program, and I'm having trouble finding an easy way to parse an option that contains a list of values. For example: --groups one,two,three. I'd like to be able to access these values in a list format as options.groups[]. Is there an optparse option to convert comma separated values into a list? Or do I have to do this manuall...

optparse - Parsing empty options in Python

I have an application that allows you to send event data to a custom script. You simply lay out the command line arguments and assign what event data goes with what argument. The problem is that there is no real flexibility here. Every option you map out is going to be used, but not every option will necessarily have data. So when the application builds the string to send to the script, some of the arguments are blank and ...

dry - Python optparse defaults vs function defaults

I'm writing a python script which I would like to be able to both call from the command line and import as a library function. Ideally the command line options and the function should use the same set of default values. What is the best way to allow me to reuse a single set of defaults in both places? Here's the current code with duplicate defaults. from optparse import OptionParser def do_stuff(op...

python - Optparse library - callback action while storing arg

My code: def main(): usage = "usage: %prog [options] arg" parser = OptionParser(usage) parser.add_option("-p", "--pending", action="callback", callback=pending, type="string", dest="test", help="View Pending Jobs") (options, args) = parser.parse_args() if x == 0: print usage, " (-h or --help for help)" print options.test if i had: script -p hello

Python optparse not seeing argument

I am trying to pass '-f nameoffile' to the program when I call it from the command line. I got this from the python sites documentation but when I pass '-f filename' or '--file=filename' it throws the error that I didnt pass enough arguments. If i pass -h the programs responds how it should and gives me the help. Any ideas? I imagine its something simple that I am overlooking. Any and all help is great, thanks, Justin.

python - Own help message using optparse

is possible to make own help message or attach own event on help option using optparse module in Python?

python - How to know if optparse option was passed in the command line or as a default

Using python, is there a way to work out whether a specific option value was set from the command line or from the default value. Ideally I would like to have a dict just like defaults, but containing the options actually supplied from command line I know that you could compare the value for each option with defaults, but this wouldn't distinguish a value was passed through command line which ...

Python optparse not working for me

I'm currently learning on how to use the Python optparse module. I'm trying the following example script but the args variable comes out empty. I tried this using Python 2.5 and 2.6 but to no avail. import optparse def main(): p = optparse.OptionParser() p.add_option('--person', '-p', action='store', dest='person', default='Me') options, args = p.parse_args() print '\n[Debug]: Print options:', opt...

python - How to give an error when no options are given with optparse

I'm try to work out how to use optparse, but I've come to a problem. My script (represented by this simplified example) takes a file, and does different things to it depending on options that are parsed to it. If no options are parsed nothing is done. It makes sense to me that because of this, an error should be given if no options are given by the user. I can't work out how to do this. I've read th...

python - Using optparse to read in a list from command line options

I am calling a python script with the following command line: --myopt="[(5.,5.),(-5.,-5.)]" The question is -- how to convert myopt to a list variable. My solution was to use optparse, treating myopt as a string, and using (options, args) = parser.parse_args() myopt = eval(options.myopt) Now, because I used eval() I feel a bi...

Still can't find your answer? Check out these communities...

PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python