Re: Python Command Line Arguments
On Saturday, April 15, 2017 at 6:45:51 PM UTC+1, Grant Edwards wrote: > On 2017-04-14, Bernd Nawothnig wrote: > > > He should switch to argparse in any case because getopt is no longer > > supported and does only receive bugfixes. > > In my book, "receiving bug fixes" means it's still supported. > > -- > Grant Just to reinforce what I said before, optparse is deprecated, not getopt. Kindest regards. Mark Lawrence. -- https://mail.python.org/mailman/listinfo/python-list
Re: Python Command Line Arguments
On Friday, April 14, 2017 at 2:44:09 PM UTC+1, Bernd Nawothnig wrote: > On 2017-04-13, Jason Friedman wrote: > >> I have this code which I got from https://www.tutorialspoint. > >> com/python/python_command_line_arguments.htm The example works fine but > >> when I modify it to what I need, it only half works. The problem is the > >> try/except. If you don't specify an input/output, they are blank at the end > >> but it shouldn't be. > >> > >> import getopt > >> import sys > > > > I am guessing you are wanting to parse command-line arguments rather than > > particularly wanting to use the getopt module. > > If I am correct you might want to spend your time instead learning the > > argparse module: > > https://docs.python.org/3/library/argparse.html > > https://docs.python.org/3/howto/argparse.html > > He should switch to argparse in any case because getopt is no longer > supported and does only receive bugfixes. > > Bernd > > -- > Die Antisemiten vergeben es den Juden nicht, dass die Juden ‘Geist’ > haben – und Geld. Die Antisemiten – ein Name der > ‘Schlechtweggekommenenen’ [Friedrich Nietzsche] optparse is deprecated, not getopt. Kindest regards. Mark Lawrence. -- https://mail.python.org/mailman/listinfo/python-list
Re: Python Command Line Arguments
On 2017-04-14, Bernd Nawothnig wrote: > He should switch to argparse in any case because getopt is no longer > supported and does only receive bugfixes. In my book, "receiving bug fixes" means it's still supported. -- Grant -- https://mail.python.org/mailman/listinfo/python-list
Re: Python Command Line Arguments
On 2017-04-13, Jason Friedman wrote: >> I have this code which I got from https://www.tutorialspoint. >> com/python/python_command_line_arguments.htm The example works fine but >> when I modify it to what I need, it only half works. The problem is the >> try/except. If you don't specify an input/output, they are blank at the end >> but it shouldn't be. >> >> import getopt >> import sys > > I am guessing you are wanting to parse command-line arguments rather than > particularly wanting to use the getopt module. > If I am correct you might want to spend your time instead learning the > argparse module: > https://docs.python.org/3/library/argparse.html > https://docs.python.org/3/howto/argparse.html He should switch to argparse in any case because getopt is no longer supported and does only receive bugfixes. Bernd -- Die Antisemiten vergeben es den Juden nicht, dass die Juden ‘Geist’ haben – und Geld. Die Antisemiten – ein Name der ‘Schlechtweggekommenenen’ [Friedrich Nietzsche] -- https://mail.python.org/mailman/listinfo/python-list
Re: Python Command Line Arguments
On Thursday, April 13, 2017 at 12:38:48 PM UTC+10, MRAB wrote: > On 2017-04-13 02:59, ian.steg...@gmail.com wrote: > > I have this code which I got from > > https://www.tutorialspoint.com/python/python_command_line_arguments.htm The > > example works fine but when I modify it to what I need, it only half works. > > The problem is the try/except. If you don't specify an input/output, they > > are blank at the end but it shouldn't be. > > > > > > import getopt > > import sys > > > > def main(argv): > > inputfile = '' > > outputfile = '' > > try: > >opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="]) > > except getopt.GetoptError: > >inputfile = 'Input' > >outputfile = 'Output' > > if inputfile == '': > >for opt, arg in opts: > > if opt == '-h': > > print ('Usage: Encrypt.py -i -o ') > > sys.exit() > > elif opt in ("-i", "--ifile"): > > inputfile = arg > > elif opt in ("-o", "--ofile"): > > outputfile = arg > > else: > >'' > > > > print 'In: ' + inputfile > > print 'Out: ' + outputfile > > > > if __name__ == "__main__": > > main(sys.argv[1:]) > > > You'll get the GetoptError exception if an option that requires an > argument doesn't have one. That's not the same as omitting the option > entirely. > > For example: > > # No -i option. > foo > > # Option -i present but without its required argument. > foo -i WOW. Thanks for that. -- https://mail.python.org/mailman/listinfo/python-list
Re: Python Command Line Arguments
On 2017-04-13 02:59, ian.steg...@gmail.com wrote: I have this code which I got from https://www.tutorialspoint.com/python/python_command_line_arguments.htm The example works fine but when I modify it to what I need, it only half works. The problem is the try/except. If you don't specify an input/output, they are blank at the end but it shouldn't be. import getopt import sys def main(argv): inputfile = '' outputfile = '' try: opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="]) except getopt.GetoptError: inputfile = 'Input' outputfile = 'Output' if inputfile == '': for opt, arg in opts: if opt == '-h': print ('Usage: Encrypt.py -i -o ') sys.exit() elif opt in ("-i", "--ifile"): inputfile = arg elif opt in ("-o", "--ofile"): outputfile = arg else: '' print 'In: ' + inputfile print 'Out: ' + outputfile if __name__ == "__main__": main(sys.argv[1:]) You'll get the GetoptError exception if an option that requires an argument doesn't have one. That's not the same as omitting the option entirely. For example: # No -i option. foo # Option -i present but without its required argument. foo -i -- https://mail.python.org/mailman/listinfo/python-list
Re: Python Command Line Arguments
> > I have this code which I got from https://www.tutorialspoint. > com/python/python_command_line_arguments.htm The example works fine but > when I modify it to what I need, it only half works. The problem is the > try/except. If you don't specify an input/output, they are blank at the end > but it shouldn't be. > > import getopt > import sys > Hello Ian, I am guessing you are wanting to parse command-line arguments rather than particularly wanting to use the getopt module. If I am correct you might want to spend your time instead learning the argparse module: https://docs.python.org/3/library/argparse.html https://docs.python.org/3/howto/argparse.html -- https://mail.python.org/mailman/listinfo/python-list
Python Command Line Arguments
I have this code which I got from https://www.tutorialspoint.com/python/python_command_line_arguments.htm The example works fine but when I modify it to what I need, it only half works. The problem is the try/except. If you don't specify an input/output, they are blank at the end but it shouldn't be. import getopt import sys def main(argv): inputfile = '' outputfile = '' try: opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="]) except getopt.GetoptError: inputfile = 'Input' outputfile = 'Output' if inputfile == '': for opt, arg in opts: if opt == '-h': print ('Usage: Encrypt.py -i -o ') sys.exit() elif opt in ("-i", "--ifile"): inputfile = arg elif opt in ("-o", "--ofile"): outputfile = arg else: '' print 'In: ' + inputfile print 'Out: ' + outputfile if __name__ == "__main__": main(sys.argv[1:]) -- https://mail.python.org/mailman/listinfo/python-list
Re: Determine actually given command line arguments
On 16.05.2013 08:08, Jussi Piitulainen wrote: Henry Leyh writes: But now I would also like to be able to _write_ such a config file FILE that can be read in a later run. And FILE should contain only those arguments that were given on the command line. Say, I tell argparse to look for arguments -s|--sopt STRING, -i|--iopt INT, -b|--bopt [BOOL], -C CONFFILE. Then 'prog -s bla -i 42 -C cfile' should produce a confparser compatible cfile which contains [my_options] sopt = blah iopt = 42 and not 'bopt = False' (if False was the program's default for bopt). Could you instead write those options that differ from the defaults? You could parse an actual command line and an empty command line, and work out the difference. So 'prog -i 3' would not cause 'iopt = 3' to be written if 3 is the default for iopt, but would that be a problem? That's what the program does at the moment. However, I'm not quite happy with it. Generally, the user doesn't know what's the default and it would be confusing if 'prog -i 3' doesn't make 'iopt = 3' turn up in the file at the end. There may also be the case when the user (for whatever reason) _wants_ the default in the file. I think I will try the opposite instead: the program writes the whole set of options to the file. This would produce a complete and consistent configuration which automatically reflects the hierarchy in which the options were set. And the user can sort it out by hand if he wants. Regards, Henry -- http://mail.python.org/mailman/listinfo/python-list
Re: Determine actually given command line arguments
Henry Leyh writes: > But now I would also like to be able to _write_ such a config file > FILE that can be read in a later run. And FILE should contain only > those arguments that were given on the command line. > > Say, I tell argparse to look for arguments -s|--sopt STRING, > -i|--iopt INT, -b|--bopt [BOOL], -C CONFFILE. Then 'prog -s bla -i > 42 -C cfile' should produce a confparser compatible cfile which > contains > >[my_options] >sopt = blah >iopt = 42 > > and not 'bopt = False' (if False was the program's default for > bopt). Could you instead write those options that differ from the defaults? You could parse an actual command line and an empty command line, and work out the difference. So 'prog -i 3' would not cause 'iopt = 3' to be written if 3 is the default for iopt, but would that be a problem? -- http://mail.python.org/mailman/listinfo/python-list
Re: Determine actually given command line arguments
On 15.05.2013 17:29, Roy Smith wrote: In article , Henry Leyh wrote: On 15.05.2013 14:24, Roy Smith wrote: In article , Henry Leyh wrote: Is there a simple way to determine which command line arguments were actually given on the commandline, i.e. does argparse.ArgumentParser() know which of its namespace members were actually hit during parse_args(). I think what you're looking for is sys.argv: $ cat argv.py import sys print sys.argv $ python argv.py foo bar ['argv.py', 'foo', 'bar'] Thanks, but as I wrote in my first posting I am aware of sys.argv and was hoping to _avoid_ using it because I'd then have to kind of re-implement a lot of the stuff already there in argparse, e.g. parsing sys.argv for short/long options, flag/parameter options etc. Sorry, I missed that. I'm not clear on exactly what you're trying to do. You say: Now I would also like the program to be able to _write_ a configparser config file that contains only the parameters actually given on the commandline. I'm guessing what you're trying to do is parse the command line first, then anything that was set there can get overridden by a value in the config file? That seems backwards. Usually, the order is: 1) built-in default 2) config file (possibly a system config file, then a per-user one) 3) environment variable 4) command-line argument It sounds like you're doing it in the reverse order -- allowing the config file to override the command line. No. The program reads a general config file in $HOME, something like ~/.programrc; then parses the command like for '-c FILE' and, if FILE is present reads it; then parses the command line remains for more arguments which overwrite everything previously set. (For the record, this split parsing is done with two argparse parsers. The first parses for '-c FILE' with parse_known_args(). If there is a FILE, its contents is used as defaults for a second parser (using set_options()) which then parses the remains that were returned by the first parser's parse_known_args().) But now I would also like to be able to _write_ such a config file FILE that can be read in a later run. And FILE should contain only those arguments that were given on the command line. Say, I tell argparse to look for arguments -s|--sopt STRING, -i|--iopt INT, -b|--bopt [BOOL], -C CONFFILE. Then 'prog -s bla -i 42 -C cfile' should produce a confparser compatible cfile which contains [my_options] sopt = blah iopt = 42 and not 'bopt = False' (if False was the program's default for bopt). Regards, Henry -- http://mail.python.org/mailman/listinfo/python-list
Re: Determine actually given command line arguments
In article , Henry Leyh wrote: >On 15.05.2013 14:24, Roy Smith wrote: >> In article , >> Henry Leyh wrote: >> >>> Is there a simple way to determine which >>> command line arguments were actually given on the commandline, i.e. does >>> argparse.ArgumentParser() know which of its namespace members were >>> actually hit during parse_args(). >> >> I think what you're looking for is sys.argv: >> >> $ cat argv.py >> import sys >> print sys.argv >> >> $ python argv.py foo bar >> ['argv.py', 'foo', 'bar'] > >Thanks, but as I wrote in my first posting I am aware of sys.argv and >was hoping to _avoid_ using it because I'd then have to kind of >re-implement a lot of the stuff already there in argparse, e.g. parsing >sys.argv for short/long options, flag/parameter options etc. Sorry, I missed that. I'm not clear on exactly what you're trying to do. You say: > Now I would also like the program to be able to _write_ a > configparser config file that contains only the parameters actually > given on the commandline. I'm guessing what you're trying to do is parse the command line first, then anything that was set there can get overridden by a value in the config file? That seems backwards. Usually, the order is: 1) built-in default 2) config file (possibly a system config file, then a per-user one) 3) environment variable 4) command-line argument It sounds like you're doing it in the reverse order -- allowing the config file to override the command line. -- http://mail.python.org/mailman/listinfo/python-list
Re: Determine actually given command line arguments
> However, maybe I could ... ... switch to getopt? Skip -- http://mail.python.org/mailman/listinfo/python-list
Re: Determine actually given command line arguments
On 15.05.2013 16:08, Skip Montanaro wrote: Yes, I was trying that and it sort of works with strings if I use something sufficiently improbable like "__UNSELECTED__" as default. But it gets difficult with boolean or even number arguments where you just may not have valid "improbable" defaults. You could now say, so what, it's the default anyway. But in my program I would like to distinguish between given and not given arguments rather than between default and non-default. Initialize all your arg variables to None, then after command line processing, any which remain as None weren't set on the command line. At that point, set them to the actual defaults. I think that's a pretty common idiom. Note: I am an old cranky dude and still use getopt. This idiom is pretty easy there. YMMV with argparse or optparse. Unfortunately, argparse wants to know the type of the argument and the boolean arguments (those with action=store_true) can't be initialized with None. However, maybe I could convert boolean arguments to something like parser.add_argument('--foo', type=str, nargs='?', const='True', default=None) I'd then have to check for string 'True' rather than for boolean True, though. Regards, Henry -- http://mail.python.org/mailman/listinfo/python-list
Re: Determine actually given command line arguments
On Wed, 15 May 2013, Henry Leyh wrote: Yes, I was trying that and it sort of works with strings if I use something sufficiently improbable like "__UNSELECTED__" as default. But it gets difficult with boolean or even number arguments where you just may not have valid "improbable" defaults. You could now say, so what, it's the default anyway. But in my program I would like to distinguish between given and not given arguments rather than between default and non-default. Have you looked into docopt? It's pretty awesome, and might really help in this case. HTH, -W -- http://mail.python.org/mailman/listinfo/python-list
Re: Determine actually given command line arguments
> Yes, I was trying that and it sort of works with strings if I use something > sufficiently improbable like "__UNSELECTED__" as default. But it gets > difficult with boolean or even number arguments where you just may not have > valid "improbable" defaults. You could now say, so what, it's the default > anyway. But in my program I would like to distinguish between given and not > given arguments rather than between default and non-default. Initialize all your arg variables to None, then after command line processing, any which remain as None weren't set on the command line. At that point, set them to the actual defaults. I think that's a pretty common idiom. Note: I am an old cranky dude and still use getopt. This idiom is pretty easy there. YMMV with argparse or optparse. Skip -- http://mail.python.org/mailman/listinfo/python-list
Re: Determine actually given command line arguments
On 15.05.2013 15:00, Oscar Benjamin wrote: On 15 May 2013 13:52, Henry Leyh wrote: On 15.05.2013 14:24, Roy Smith wrote: In article , Henry Leyh wrote: Is there a simple way to determine which command line arguments were actually given on the commandline, i.e. does argparse.ArgumentParser() know which of its namespace members were actually hit during parse_args(). I think what you're looking for is sys.argv: $ cat argv.py import sys print sys.argv $ python argv.py foo bar ['argv.py', 'foo', 'bar'] Thanks, but as I wrote in my first posting I am aware of sys.argv and was hoping to _avoid_ using it because I'd then have to kind of re-implement a lot of the stuff already there in argparse, e.g. parsing sys.argv for short/long options, flag/parameter options etc. I was thinking of maybe some sort of flag that argparse sets on those optional arguments created with add_argument() that are really given on the command line, i.e. those that it stumbles upon them during parse_args(). I don't know about that but I imagine that you could compare values with their defaults to see which have been changed. Yes, I was trying that and it sort of works with strings if I use something sufficiently improbable like "__UNSELECTED__" as default. But it gets difficult with boolean or even number arguments where you just may not have valid "improbable" defaults. You could now say, so what, it's the default anyway. But in my program I would like to distinguish between given and not given arguments rather than between default and non-default. Regards, Henry -- http://mail.python.org/mailman/listinfo/python-list
Re: Determine actually given command line arguments
On 15 May 2013 13:52, Henry Leyh wrote: > On 15.05.2013 14:24, Roy Smith wrote: >> >> In article , >> Henry Leyh wrote: >> >>> Is there a simple way to determine which >>> command line arguments were actually given on the commandline, i.e. does >>> argparse.ArgumentParser() know which of its namespace members were >>> actually hit during parse_args(). >> >> >> I think what you're looking for is sys.argv: >> >> $ cat argv.py >> import sys >> print sys.argv >> >> $ python argv.py foo bar >> ['argv.py', 'foo', 'bar'] > > Thanks, but as I wrote in my first posting I am aware of sys.argv and was > hoping to _avoid_ using it because I'd then have to kind of re-implement a > lot of the stuff already there in argparse, e.g. parsing sys.argv for > short/long options, flag/parameter options etc. > > I was thinking of maybe some sort of flag that argparse sets on those > optional arguments created with add_argument() that are really given on the > command line, i.e. those that it stumbles upon them during parse_args(). I don't know about that but I imagine that you could compare values with their defaults to see which have been changed. Oscar -- http://mail.python.org/mailman/listinfo/python-list
Re: Determine actually given command line arguments
On 15.05.2013 14:24, Roy Smith wrote: In article , Henry Leyh wrote: Is there a simple way to determine which command line arguments were actually given on the commandline, i.e. does argparse.ArgumentParser() know which of its namespace members were actually hit during parse_args(). I think what you're looking for is sys.argv: $ cat argv.py import sys print sys.argv $ python argv.py foo bar ['argv.py', 'foo', 'bar'] Thanks, but as I wrote in my first posting I am aware of sys.argv and was hoping to _avoid_ using it because I'd then have to kind of re-implement a lot of the stuff already there in argparse, e.g. parsing sys.argv for short/long options, flag/parameter options etc. I was thinking of maybe some sort of flag that argparse sets on those optional arguments created with add_argument() that are really given on the command line, i.e. those that it stumbles upon them during parse_args(). Regards, Henry -- http://mail.python.org/mailman/listinfo/python-list
Re: Determine actually given command line arguments
Colin J. Williams writes: > On 15/05/2013 2:34 AM, Henry Leyh wrote: > > Hello, > > I am writing a program that gets its parameters from a combination > > of config file (using configparser) and command line arguments > > (using argparse). Now I would also like the program to be able to > > _write_ a configparser config file that contains only the > > parameters actually given on the commandline. Is there a simple > > way to determine which command line arguments were actually given > > on the commandline, i.e. does argparse.ArgumentParser() know which > > of its namespace members were actually hit during parse_args(). > > > > I have tried giving the arguments default values and then looking > > for those having a non-default value but this is really awkward, > > especially if it comes to non-string arguments. Also, parsing > > sys.argv looks clumsy because you have to keep track of short and > > long options with and without argument etc. i.e. all things that I > > got argparse for in the first place. > > > > Thanks && Greetings, > > Henry > Try sys.argv You people should read what you quote, or what you don't quote when you cut the relevant portion. Q. ... parsing sys.argv looks clumsy because ... A. Try sys.argv I mean, huh? -- http://mail.python.org/mailman/listinfo/python-list
Re: Determine actually given command line arguments
On 05/15/2013 08:24 AM, Roy Smith wrote: In article , Henry Leyh wrote: Is there a simple way to determine which command line arguments were actually given on the commandline, i.e. does argparse.ArgumentParser() know which of its namespace members were actually hit during parse_args(). I think what you're looking for is sys.argv: $ cat argv.py import sys print sys.argv $ python argv.py foo bar ['argv.py', 'foo', 'bar'] Colin & Roy: The OP mentioned sys.argv in his original query. -- DaveA -- http://mail.python.org/mailman/listinfo/python-list
Re: Determine actually given command line arguments
In article , Henry Leyh wrote: > Is there a simple way to determine which > command line arguments were actually given on the commandline, i.e. does > argparse.ArgumentParser() know which of its namespace members were > actually hit during parse_args(). I think what you're looking for is sys.argv: $ cat argv.py import sys print sys.argv $ python argv.py foo bar ['argv.py', 'foo', 'bar'] -- http://mail.python.org/mailman/listinfo/python-list
Re: Determine actually given command line arguments
On 15/05/2013 2:34 AM, Henry Leyh wrote: Hello, I am writing a program that gets its parameters from a combination of config file (using configparser) and command line arguments (using argparse). Now I would also like the program to be able to _write_ a configparser config file that contains only the parameters actually given on the commandline. Is there a simple way to determine which command line arguments were actually given on the commandline, i.e. does argparse.ArgumentParser() know which of its namespace members were actually hit during parse_args(). I have tried giving the arguments default values and then looking for those having a non-default value but this is really awkward, especially if it comes to non-string arguments. Also, parsing sys.argv looks clumsy because you have to keep track of short and long options with and without argument etc. i.e. all things that I got argparse for in the first place. Thanks && Greetings, Henry Try sys.argv Colin W. -- http://mail.python.org/mailman/listinfo/python-list
Determine actually given command line arguments
Hello, I am writing a program that gets its parameters from a combination of config file (using configparser) and command line arguments (using argparse). Now I would also like the program to be able to _write_ a configparser config file that contains only the parameters actually given on the commandline. Is there a simple way to determine which command line arguments were actually given on the commandline, i.e. does argparse.ArgumentParser() know which of its namespace members were actually hit during parse_args(). I have tried giving the arguments default values and then looking for those having a non-default value but this is really awkward, especially if it comes to non-string arguments. Also, parsing sys.argv looks clumsy because you have to keep track of short and long options with and without argument etc. i.e. all things that I got argparse for in the first place. Thanks && Greetings, Henry -- http://mail.python.org/mailman/listinfo/python-list
Re: Question About Command line arguments
On 10/06/11 20:03:44, Kurt Smith wrote: On Fri, Jun 10, 2011 at 12:58 PM, Mark Phillips wrote: How do I write my script so it picks up argument from the output of commands that pipe input into my script? def main(): import sys print sys.stdin.read() if __name__ == '__main__': main() $ echo "fred" | python script.py fred $ $ cat script.py def main(): print raw_input() if __name__ == '__main__': main() $ echo "fred" | python script.py fred $ Hope this helps, -- HansM -- http://mail.python.org/mailman/listinfo/python-list
Re: Question About Command line arguments
On 06/10/2011 04:00 PM, Benjamin Kaplan wrote: On Fri, Jun 10, 2011 at 11:31 AM, Tim Chase if os.isatty(sys.stdin): #<-- this check Any reason for that over sys.stdin.isatty()? my knowledge of os.isatty() existing and my previous lack of knowledge about sys.stdin.isatty() :) -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: Question About Command line arguments
On Fri, Jun 10, 2011 at 11:31 AM, Tim Chase wrote: > On 06/10/2011 12:58 PM, Mark Phillips wrote: >> >> How do I write my script so it picks up argument from the >> output of commands that pipe input into my script? > > You can check > > if os.isatty(sys.stdin): # <-- this check Any reason for that over sys.stdin.isatty()? -- http://mail.python.org/mailman/listinfo/python-list
Re: Question About Command line arguments
On Fri, Jun 10, 2011 at 1:33 PM, Dennis wrote: > On Fri, Jun 10, 2011 at 11:58 AM, Mark Phillips > fred > > ['alice'] > fred Just realized the if/else will have to be changed slightly if we want to output both argv and stdin. -- http://mail.python.org/mailman/listinfo/python-list
Re: Question About Command line arguments
On Fri, Jun 10, 2011 at 11:58 AM, Mark Phillips wrote: \ > > Kurt, > > How does one write a main method to handle both command line args and stdin > args? Here is what I came up with: The one weird thing, the line from above didn't seem to work so I changed it if os.isatty(sys.stdin): to this: if not os.isatty(sys.stdin.fileno()): Below 3 tests, with stdin redirection, then with one argument, then with both stdin redirection and one argument, the results are at the very bottom. $ cat ./argvtest.py; echo "fred" | ./argvtest.py ; ./argvtest.py "alice"; echo "fred" | ./argvtest.py "bob" #!/usr/bin/python import os import sys def main(): #This checks to see if stdin is a not tty and > 0 if not os.isatty(sys.stdin.fileno()): arg = sys.stdin.read() print arg elif len(sys.argv[1:]) > 0: # if the length of the first argument is > 0 #[1:] strip the first string beacause it is the name of the script arg = sys.argv[1:] print arg if __name__ == "__main__": main() fred ['alice'] fred > > Thanks, > > Mark > Welcome, Dennis O. > -- > http://mail.python.org/mailman/listinfo/python-list > > -- http://mail.python.org/mailman/listinfo/python-list
Re: Question About Command line arguments
On Jun 10, 2011 10:26 AM, "Mark Phillips" wrote: > > I have a script that processes command line arguments > > def main(argv=None): > syslog.syslog("Sparkler stared processing") > if argv is None: > argv = sys.argv > if len(argv) != 2: > syslog.syslog(usage()) > else: > r = parseMsg(sys.argv[1]) > syslog.syslog(r) > return 0 > > if __name__ == "__main__": > sys.exit(main()) > > When I run "python myscript fred" it works as expected - the argument fred is processed in parseMsg as sys.arv[1] > > When I run "echo fred | python myscript" the script thinks there are no arguments, so it prints out the usage statement. > > Is the problem with the echo command, or how I wrote my script? > > Thanks! > > Mark > Nothing wrong with either. The problem is a misunderstanding in how the command line works. When you write "python myscript fred", the shell calls the python executable and passes the arguments "myscript" and "fred" to the main function. In the second example, the shell calls "python myscript" and then sends echo's stdout in to python's stdin. It's not passed as an argument. If you were to call raw_input() on the second example, it would return "fred" without prompting you for anything because raw_input reads from stdin which in this case is the result of echo. > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: Question About Command line arguments
On 6/10/11 12:58 PM, Mark Phillips wrote: On Fri, Jun 10, 2011 at 10:41 AM, MRAB mailto:pyt...@mrabarnett.plus.com>> wrote: On 10/06/2011 18:21, Mark Phillips wrote: I have a script that processes command line arguments def main(argv=None): syslog.syslog("Sparkler stared processing") if argv is None: argv = sys.argv if len(argv) != 2: syslog.syslog(usage()) else: r = parseMsg(sys.argv[1]) syslog.syslog(r) return 0 if __name__ == "__main__": sys.exit(main()) When I run "python myscript fred" it works as expected - the argument fred is processed in parseMsg as sys.arv[1] When I run "echo fred | python myscript" the script thinks there are no arguments, so it prints out the usage statement. Is the problem with the echo command, or how I wrote my script? In the second case, there aren't any arguments. The echo command is writing "fred" to its standard output, which is attached to your script's standard input. How do I write my script so it picks up argument from the output of commands that pipe input into my script? You may want to just use the appropriate shell syntax instead: $ python myscript `echo fred` -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco -- http://mail.python.org/mailman/listinfo/python-list
Re: Question About Command line arguments
On Fri, Jun 10, 2011 at 11:03 AM, Kurt Smith wrote: > On Fri, Jun 10, 2011 at 12:58 PM, Mark Phillips > wrote: > > How do I write my script so it picks up argument from the output of > commands > > that pipe input into my script? > > def main(): >import sys >print sys.stdin.read() > > if __name__ == '__main__': >main() > > $ echo "fred" | python script.py > fred > $ > Kurt, How does one write a main method to handle both command line args and stdin args? Thanks, Mark -- http://mail.python.org/mailman/listinfo/python-list
Re: Question About Command line arguments
On 06/10/2011 12:58 PM, Mark Phillips wrote: How do I write my script so it picks up argument from the output of commands that pipe input into my script? You can check if os.isatty(sys.stdin): # <-- this check do_stuff_with_the_terminal() else: read_options_from_stdin() -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: Question About Command line arguments
On Fri, Jun 10, 2011 at 11:03 AM, Dennis wrote: > On Fri, Jun 10, 2011 at 10:58 AM, Mark Phillips > wrote: >> On Fri, Jun 10, 2011 at 10:41 AM, MRAB wrote: >> >> On 10/06/2011 18:21, Mark Phillips wrote: > >> > How do I write my script so it picks up argument from the output of commands > that pipe input into my script? I think if you want to replicate stdin behaviour try looking into the xargs command, assuming that is available on your platform. However reading in stdin into argv may be more elegant, but slightly unexpected to the experienced user. Dennis O. -- http://mail.python.org/mailman/listinfo/python-list
Re: Question About Command line arguments
On Fri, Jun 10, 2011 at 12:58 PM, Mark Phillips wrote: > How do I write my script so it picks up argument from the output of commands > that pipe input into my script? def main(): import sys print sys.stdin.read() if __name__ == '__main__': main() $ echo "fred" | python script.py fred $ -- http://mail.python.org/mailman/listinfo/python-list
Re: Question About Command line arguments
On Fri, Jun 10, 2011 at 10:41 AM, MRAB wrote: > On 10/06/2011 18:21, Mark Phillips wrote: > >> I have a script that processes command line arguments >> >> def main(argv=None): >> syslog.syslog("Sparkler stared processing") >> if argv is None: >> argv = sys.argv >> if len(argv) != 2: >> syslog.syslog(usage()) >> else: >> r = parseMsg(sys.argv[1]) >> syslog.syslog(r) >> return 0 >> >> if __name__ == "__main__": >> sys.exit(main()) >> >> When I run "python myscript fred" it works as expected - the argument >> fred is processed in parseMsg as sys.arv[1] >> >> When I run "echo fred | python myscript" the script thinks there are no >> arguments, so it prints out the usage statement. >> >> Is the problem with the echo command, or how I wrote my script? >> >> In the second case, there aren't any arguments. The echo command is > writing "fred" to its standard output, which is attached to your > script's standard input. > > How do I write my script so it picks up argument from the output of commands that pipe input into my script? Mark -- http://mail.python.org/mailman/listinfo/python-list
Re: Question About Command line arguments
On 10/06/2011 18:21, Mark Phillips wrote: I have a script that processes command line arguments def main(argv=None): syslog.syslog("Sparkler stared processing") if argv is None: argv = sys.argv if len(argv) != 2: syslog.syslog(usage()) else: r = parseMsg(sys.argv[1]) syslog.syslog(r) return 0 if __name__ == "__main__": sys.exit(main()) When I run "python myscript fred" it works as expected - the argument fred is processed in parseMsg as sys.arv[1] When I run "echo fred | python myscript" the script thinks there are no arguments, so it prints out the usage statement. Is the problem with the echo command, or how I wrote my script? In the second case, there aren't any arguments. The echo command is writing "fred" to its standard output, which is attached to your script's standard input. -- http://mail.python.org/mailman/listinfo/python-list
Question About Command line arguments
I have a script that processes command line arguments def main(argv=None): syslog.syslog("Sparkler stared processing") if argv is None: argv = sys.argv if len(argv) != 2: syslog.syslog(usage()) else: r = parseMsg(sys.argv[1]) syslog.syslog(r) return 0 if __name__ == "__main__": sys.exit(main()) When I run "python myscript fred" it works as expected - the argument fred is processed in parseMsg as sys.arv[1] When I run "echo fred | python myscript" the script thinks there are no arguments, so it prints out the usage statement. Is the problem with the echo command, or how I wrote my script? Thanks! Mark -- http://mail.python.org/mailman/listinfo/python-list
Re: Parse config file and command-line arguments, to get a single collection of options
Ben Finney wrote in news:87k4deaxfc@benfinney.id.au: > Howdy all, > > Python's standard library has modules for configuration file > parsing (configparser) and command-line argument parsing > (optparse, argparse). I want to write a program that does both, > but also: > > * Has a cascade of options: default option values, overridden by > config > file options, overridden by command-line options. > > * Reads a different, or even additional, configuration file if > specified > on the command-line (e.g. --config-file foo.conf) and yet still > obeys the above cascade. > > * Allows a single definition of an option (e.g. logging level) to > define > the same option for parsing from configuration files and the > command line. > > * Unifies the parsed options into a single collection for the > rest of > the program to access without caring where they came from. > > How can I achieve this with minimum deviation from the Python > standard library? > > > (For anyone interested in gaining StackOverflow points, I'm also > asking this as a question there so feel free to post answers on > that site > http://stackoverflow.com/questions/6133517/parse-config-file- > and-command-line-arguments-to-get-a-single-collection-of-optio>.) > This seems vaguely similar to a module I wrote and use all the time. It allows default value specification, categorization of command-line options, in-line parsing of further spec file[s] and overrides of values in the the sequence you define, pretty much. It doesn't deal with the "logging level" item. I'm not sure what that would mean. The idea of the module is to create a namespace object (though it could as easily be a dict) that contains whatever values are specified. in the program it would be invoked like this: ctx = Cmdline( outfname='test.out', size=(250,400), ... ) (or whatever). The command line can contain switches, prefixed by hyphens, spec file names, prefixed by @, untagged names, or key=value pairs. The values will be parsed as (tuples), [lists], or {dicts}, ints, floats, or strings. I did not, I am ashamed to say, resist the temptation to guess. 'Ctx' will contain the result of all this. Switches, if any are in a list named ctx._switches, unadorned arguments are in a list named ctx._vars, and the other stuff is pretty much as you would expect. It expects configuration files to be in a sort of ini-file format. Here's an example: --- test.spec: log=test.log count=10 size=(400,200) group1={key=value,a=alpha} group2={b=beta,name=doogie howser} # temp=[1,2,5,11,22] sub=(al,becky,carl,diane,edwin,fran) --- test.py: from Cmdline import Cmdline c = Cmdline( count=5, log='pink.tank') c.show() --- >python test.py log=friend.txt @test.spec count=32 name=waldo ... yields: count = 32 sub = ('al', 'becky', 'carl', 'diane', 'edwin', 'fran') log = 'test.log' temp = [1, 2, 5, 11, 22] group1 = {'a': 'alpha', 'key': 'value'} group2 = {'b': 'beta', 'name': 'doogie howser'} size = (400, 200) name = 'waldo' ... while >python @test.spec count=32 name=waldo temp=Vitalis sub='' dream -k count = 32 _vars = ['dream'] log = 'test.log' temp = 'Vitalis' _switches = ['k'] name = 'waldo' group1 = {'a': 'alpha', 'key': 'value'} group2 = {'b': 'beta', 'name': 'doogie howser'} size = (400, 200) sub = '' What the program does with the results is up to it, of course. -- rzed -- http://mail.python.org/mailman/listinfo/python-list
Re: Parse config file and command-line arguments, to get a single collection of options
On May 25, 9:38 pm, Ben Finney wrote: > Howdy all, > > Python's standard library has modules for configuration file parsing > (configparser) and command-line argument parsing (optparse, argparse). I > want to write a program that does both, but also: > > * Has a cascade of options: default option values, overridden by config > file options, overridden by command-line options. > > * Reads a different, or even additional, configuration file if specified > on the command-line (e.g. --config-file foo.conf) and yet still obeys > the above cascade. > > * Allows a single definition of an option (e.g. logging level) to define > the same option for parsing from configuration files and the command > line. > > * Unifies the parsed options into a single collection for the rest of > the program to access without caring where they came from. > > How can I achieve this with minimum deviation from the Python standard > library? One thought is start with something like ChainMap, http://code.activestate.com/recipes/305268-chained-map-lookups/?in=user-178123 , or some variant to unify multiple mapping objects into a single prioritized collection. A mapping for command line args can be made by using vars() on an argparse namespace to create a dictionary. ConfigParser's mapping is accessible via its get() method. With a ChainMap style object you can add other option sources such as os.environ. This should get you started on your grand unified, do- everything-at-once vision with minimal deviation from the standard library. Raymond -- http://mail.python.org/mailman/listinfo/python-list
Parse config file and command-line arguments, to get a single collection of options
Howdy all, Python's standard library has modules for configuration file parsing (configparser) and command-line argument parsing (optparse, argparse). I want to write a program that does both, but also: * Has a cascade of options: default option values, overridden by config file options, overridden by command-line options. * Reads a different, or even additional, configuration file if specified on the command-line (e.g. --config-file foo.conf) and yet still obeys the above cascade. * Allows a single definition of an option (e.g. logging level) to define the same option for parsing from configuration files and the command line. * Unifies the parsed options into a single collection for the rest of the program to access without caring where they came from. How can I achieve this with minimum deviation from the Python standard library? (For anyone interested in gaining StackOverflow points, I'm also asking this as a question there so feel free to post answers on that site http://stackoverflow.com/questions/6133517/parse-config-file-and-command-line-arguments-to-get-a-single-collection-of-optio>.) -- \ “Apologize, v. To lay the foundation for a future offense.” | `\ —Ambrose Bierce, _The Devil's Dictionary_, 1906 | _o__) | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: Running a script with command line arguments
> Hi, > I'm new to python and trying to run a borrowed script. The error I > get suggests that I need to give a proper command to run it. The > input file is "c26_1plus.csv" and the intended output file is > "c26_1plus_backbone.csv". > > Can anyone help? > The usage string in the script says that the required arguments are: input_file output_file backbone_alpha [file delimiter] You're providing "input_file" and "output_file" but not "backbone_alpha". -- http://mail.python.org/mailman/listinfo/python-list
Re: Ideas for a module to process command line arguments
You may be interested in a little Python module I wrote to make handling of command line arguments even easier (open source and free to use) - http://freshmeat.net/projects/commando > On Tuesday, January 11, 2011 12:18 AM Sohail wrote: > Hey, every body has their own favorite method/ways to process command line > arguments. I have worked on a little CPython extension to handle command line > arguments may be you will find it interesting and useful > > To download the source code > http://www.stupidcomputing.com/page.php?id=argsv > > Thank you. >> On Tuesday, January 11, 2011 2:25 AM Alice_Bevan?McGregor wrote: >> On 2011-01-10 21:18:41 -0800, Sohail said: >> >> >> Even I have implemented my own way to handle command-line scripts, >> marrow.script: >> >> https://github.com/pulp/marrow.script >> >> The idea with mine that you write a Python function... and that is it. >> The latest version has experimental support for class-based >> "subcommand" dispatch, but it needs work, needs to be updated to >> support sub-sub commands, and the help text generator needs to be >> overhauled to support classes properly. >> >> The argument list, typecasting, etc. is built from the argspec. Help >> text is pulled from the docstring. Decorators are provided to override >> short names, define explicit callbacks or typecasting functions, etc. >> >> I got tired of using PasteScript and OptParse. Mostly OptParse, actually. >> :/ >> >> - Alice. >>> On Tuesday, January 11, 2011 3:32 AM Michele Simionato wrote: >>> explicit callbacks or typecasting functions, etc. >>> ly. =A0:/ >>> >>> >>> it is a pity that the argument parsing modules in the standard library >>> are so verbose that everybody is reinventing the same thing :-( It >>> looks like you have reinvented plac: http://pypi.python.org/pypi/plac >>>> On Tuesday, January 11, 2011 9:37 AM Alice_Bevan?McGregor wrote: >>>> On 2011-01-11 00:32:32 -0800, Michele Simionato said: >>>> >>>> And a package called `commandline`. There are many command line >>>> parsing modules, many of which are unmaintained, few have reached 1.0. >>>> >>>> My criteria for 1.0? 100% unit test coverage, complete documentation, >>>> compatibility with 2.6+ and 3.1+ within a single package. >>>> marrow.script meets that criteria, do the others? :) >>>> >>>> - Alice. >>>>> On Tuesday, January 11, 2011 10:06 AM Alice_Bevan?McGregor wrote: >>>>> On 2011-01-11 00:32:32 -0800, Michele Simionato said: >>>>> >>>>> After looking into it, Plac's default help display is not very helpful; >>>>> you need to massage your application a fair amount before generating >>>>> nice, complete-looking argument lists and such. For example: >>>>> >>>>> def main(verbose: ('prints more info', 'flag', 'v'), dsn: 'connection >>>>> string'): >>>>> >>>>> @annotate(dsn="connection string", verbose="prints more info") >>>>> def main(dsn, verbose=False): >>>>> >>>>> The latter is marrow.script, and even without the annotation a more >>>>> complete help text is generated. The -v and flag nature are assumed >>>>> from the first unique character and default value. (Flags, when >>>>> present on the command line, invert the default value.) Py3k >>>>> annotations have not been implemented yet, though. >>>>> >>>>> Also included is an easy way to simulte command-line execution (i.e. by >>>>> reading arguments passed by hand and by returning the exit code, vs. >>>>> reading sys.argv and calling sys.exit()) for unit testing purposes. >>>>> Plac appears (from the documentation) to be written on top of argparse. >>>>> >>>>> - Alice. >>>>>> On Tuesday, January 11, 2011 10:49 AM Michele Simionato wrote: >>>>>> And the problem with that being what? >>>>>>> On Tuesday, January 11, 2011 11:22 AM Jean-Michel Pichavant wrote: >>>>>>> Michele Simionato wrote: >>>>>>> ... not available to python 2.5 / 2.6 users :) >>>>>>> >>>>>>> JM >>>>>>>> On Tuesday, January 11, 2011 11:26 AM Michele Simionato wrote: >>>>>
Re: plac, the easiest command line arguments parser in the world
You may be interested in a little Python module I wrote to make handling of command line arguments even easier (open source and free to use) - http://freshmeat.net/projects/commando > On Wednesday, June 02, 2010 12:37 AM Michele Simionato wrote: > I would like to announce to the world the first public release of > plac: > > http://pypi.python.org/pypi/plac > > Plac is a wrapper over argparse and works in all versions of > Python starting from Python 2.3 up to Python 3.1. > > With blatant immodesty, plac claims to be the easiest to use command > line arguments parser module in the Python world. Its goal is to > reduce the > learning curve of argparse from hours to minutes. It does so by > removing the need to build a command line arguments parser by hand: > actually it is smart enough to infer the parser from function > annotations. > > Here is a simple example (in Python 3) to wet your appetite: > > $ cat example.py > def main(arg: "required argument"): > "do something with arg" > print('Got %s' % arg) > > if __name__ == '__main__': > import plac; plac.call(main) # passes sys.argv[1:] to main > > $ python example.py -h > usage: example.py [-h] arg > > do something with arg > > positional arguments: > arg required argument > > optional arguments: > -h, --help show this help message and exit > > > $ python example.py > usage: example.py [-h] arg > example.py: error: too few arguments > > $ python example.py arg > Got arg > > $ python example.py arg1 arg2 > usage: example.py [-h] arg > example.py: error: unrecognized arguments: arg2 > > You can find in the documentation a lot of other simple and not so > simple > examples: > > http://micheles.googlecode.com/hg/plac/doc/plac.html > > > Enjoy! > > Michele Simionato > > P.S. answering an unspoken question: yes, we really needed yet > another > command line arguments parser! ;) >> On Wednesday, June 02, 2010 4:28 AM Tim Golden wrote: >> On 02/06/2010 05:37, Michele Simionato wrote: >> >> I like it. I am a constant user of the >> >> def main (a, b=1, c=2): >> >> if __name__ == '__main__': >> main (*sys.argv[1:]) >> >> pattern, which provides a minimally semi-self-documenting >> approach for positional args, but I have always found the existing >> offerings just a little too much work to bother with. >> I will give plac a run and see how it behaves. >> >> Thanks >> >> TJG >>> On Wednesday, June 02, 2010 4:43 AM Paul Rubin wrote: >>> Tim Golden writes: >>> >>> After using optparse a couple of times I got the hang of it. Maybe its >>> docs could be organized a bit better, but it does the obvious things >>> conveniently once you have figured it out a bit. >>>> On Wednesday, June 02, 2010 4:49 AM Michele Simionato wrote: >>>> Notice that optparse is basically useless in the use case Tim is >>>> considering (positional arguments) since it only manages options. >>>>> On Wednesday, June 02, 2010 4:52 AM Jean-Michel Pichavant wrote: >>>>> Michele Simionato wrote: >>>>> Thanks for participating. >>>>> >>>>> JM >>>>>> On Wednesday, June 02, 2010 5:01 AM Stefan Behnel wrote: >>>>>> Paul Rubin, 02.06.2010 10:43: >>>>>> >>>>>> Same from here. I managed to talk a Java-drilled collegue of mine into >>>>>> writing a Python script for a little command line utility, but he needed >>>>>> a >>>>>> way to organise his argument extraction code when the number of arguments >>>>>> started to grow beyond two. I told him that there were two ways to do it: >>>>>> do it by hand or do it right. He took the right choice and I took him to >>>>>> the optparse docs, copied the first example into his code and we adapted >>>>>> it >>>>>> a little. He just loved the beauty of it. >>>>>> >>>>>> Stefan >>>>>>> On Wednesday, June 02, 2010 5:14 AM Michele Simionato wrote: >>>>>>> a >>>>>>> it >>>>>>> >>>>>>> Could you show plac to your friend? I would be curious to know what he >>>>>>> think. >>>>>>> Perhaps he would call out his judgment on optparse ;) >>>>>>>> On Wednesday, June 02, 2010 6:42 AM Antoine Pitro
Re: Ideas for a module to process command line arguments
On Jan 12, 6:09 pm, Alice Bevan–McGregor wrote: > entirely sure what you mean by 'smart' options. If your'e referring to > using a single hyphen and a list of characters to represent a long > option (which, to the rest of the world, use two leading hyphens) then > that's pretty weird. ;) > > One major system in the world that doesn't really differentiate between > long and short options is... DOS, and by extension, Windows. But they > also use / as a switch character. Yes, and plac (it is argparse actually) can accomodate the Windows convention by setting the prefix_chars to "/". I wanted to be able to give that freedom even if personally am more used to the GNU double-dash convention. > Anyway; I'm happy with what I have wrought (and am continuing to update > with support for class-based sub-command dispatch) and will be > utilizing it for all scripts in the Marrow suite. To each their own, > but reinvention itself can be for motivations other than NIH. I wanted > something pure-Python, portable across the 3k barrier without code > modification (no 2to3), that didn't use optparse, getopt, or argparse > and basically be a translation layer. It can be simpler than that, as > marrow.script demonstrates. No arguing against that. BTW, I was not criticizing marrow.script, I was simply deploring the situation in the standard library. If the same approach for parsing command-line options is being reinvented by different people multiple times there must be something wrong with the current standard. -- http://mail.python.org/mailman/listinfo/python-list
Re: Ideas for a module to process command line arguments
On 2011-01-11 21:41:24 -0800, Michele Simionato said: Originally plac too was able to recognize flags automatically by looking at the default value (if the default value is a boolean then the option is a flag); however I removed that functionality because I wanted to be able to differentiate between flag and (smart) options (see http://micheles.googlecode.com/hg/plac/doc/plac.html#scripts-with-options-and-smart-options). Not entirely sure what you mean by 'smart' options. If your'e referring to using a single hyphen and a list of characters to represent a long option (which, to the rest of the world, use two leading hyphens) then that's pretty weird. ;) Consider most of the GNU tools: ls -lvh tar -xzvf file.tgz (goes so far as to make the leading hyphen optional!) less -ceF logfile bc -qw ps -aux (same as tar) And even third-party tools: mysql -fH pg_dump -abO ... One major system in the world that doesn't really differentiate between long and short options is... DOS, and by extension, Windows. But they also use / as a switch character. Anyway; I'm happy with what I have wrought (and am continuing to update with support for class-based sub-command dispatch) and will be utilizing it for all scripts in the Marrow suite. To each their own, but reinvention itself can be for motivations other than NIH. I wanted something pure-Python, portable across the 3k barrier without code modification (no 2to3), that didn't use optparse, getopt, or argparse and basically be a translation layer. It can be simpler than that, as marrow.script demonstrates. - Alice. -- http://mail.python.org/mailman/listinfo/python-list
Re: Ideas for a module to process command line arguments
On Jan 11, 6:57 pm, Mike wrote: > On Jan 11, 11:26 am, Michele Simionato > wrote: > > In that case easy_install/pip/whatever will install the dependency > > automatically (who is installing > > dependencies by hand nowadays?). > > I do. Is this bad? :} You are simply spending more time than needed, since there are already tools available to perform the task for you. -- http://mail.python.org/mailman/listinfo/python-list
Re: Ideas for a module to process command line arguments
On Jan 11, 4:06 pm, Alice Bevan–McGregor wrote: > After looking into it, Plac's default help display isn't very helpful; > you need to massage your application a fair amount before generating > nice, complete-looking argument lists and such. For example: > > def main(verbose: ('prints more info', 'flag', 'v'), dsn: 'connection > string'): > > @annotate(dsn="connection string", verbose="prints more info") > def main(dsn, verbose=False): > > The latter is marrow.script, and even without the annotation a more > complete help text is generated. The -v and flag nature are assumed > from the first unique character and default value. (Flags, when > present on the command line, invert the default value.) Honestly I do not see any significant difference both in the level of verbosity for the annotations and in the quality of the help message provided in the absence of annotations. Originally plac too was able to recognize flags automatically by looking at the default value (if the default value is a boolean then the option is a flag); however I removed that functionality because I wanted to be able to differentiate between flag and (smart) options (see http://micheles.googlecode.com/hg/plac/doc/plac.html#scripts-with-options-and-smart-options). -- http://mail.python.org/mailman/listinfo/python-list
Re: Ideas for a module to process command line arguments
On Jan 11, 11:26 am, Michele Simionato wrote: > > In that case easy_install/pip/whatever will install the dependency > automatically (who is installing > dependencies by hand nowadays?). More seriously I thought being based I do. Is this bad? :} -- http://mail.python.org/mailman/listinfo/python-list
Re: Ideas for a module to process command line arguments
On Jan 11, 5:22 pm, Jean-Michel Pichavant wrote: > Michele Simionato wrote: > > On Jan 11, 4:06 pm, Alice Bevan McGregor wrote: > > >> Plac appears (from the documentation) to be written on top of argparse. > >> :( > > > And the problem with that being what? > > ... not available to python 2.5 / 2.6 users :) > > JM In that case easy_install/pip/whatever will install the dependency automatically (who is installing dependencies by hand nowadays?). More seriously I thought being based on a solid module which is also part of the standard library (for Python 2.7+) was an asset of plac. -- http://mail.python.org/mailman/listinfo/python-list
Re: Ideas for a module to process command line arguments
Michele Simionato wrote: On Jan 11, 4:06 pm, Alice Bevan–McGregor wrote: Plac appears (from the documentation) to be written on top of argparse. :( And the problem with that being what? ... not available to python 2.5 / 2.6 users :) JM -- http://mail.python.org/mailman/listinfo/python-list
Re: Ideas for a module to process command line arguments
On Jan 11, 4:06 pm, Alice Bevan–McGregor wrote: > Plac appears (from the documentation) to be written on top of argparse. > :( And the problem with that being what? -- http://mail.python.org/mailman/listinfo/python-list
Re: Ideas for a module to process command line arguments
On 2011-01-11 00:32:32 -0800, Michele Simionato said: It's a pity that the argument parsing modules in the standard library are so verbose that everybody is reinventing the same thing :-( It looks like you have reinvented plac: http://pypi.python.org/pypi/plac After looking into it, Plac's default help display isn't very helpful; you need to massage your application a fair amount before generating nice, complete-looking argument lists and such. For example: def main(verbose: ('prints more info', 'flag', 'v'), dsn: 'connection string'): @annotate(dsn="connection string", verbose="prints more info") def main(dsn, verbose=False): The latter is marrow.script, and even without the annotation a more complete help text is generated. The -v and flag nature are assumed from the first unique character and default value. (Flags, when present on the command line, invert the default value.) Py3k annotations haven't been implemented yet, though. Also included is an easy way to simulte command-line execution (i.e. by reading arguments passed by hand and by returning the exit code, vs. reading sys.argv and calling sys.exit()) for unit testing purposes. Plac appears (from the documentation) to be written on top of argparse. :( - Alice. -- http://mail.python.org/mailman/listinfo/python-list
Re: Ideas for a module to process command line arguments
On 2011-01-11 00:32:32 -0800, Michele Simionato said: On Jan 11, 8:25 am, Alice Bevan–McGregor wrote: I got tired of using PasteScript and OptParse. Mostly OptParse, actually. :/ It's a pity that the argument parsing modules in the standard library are so verbose that everybody is reinventing the same thing :-( It looks like you have reinvented plac: http://pypi.python.org/pypi/plac And a package called `commandline`. There are many command line parsing modules, many of which are unmaintained, few have reached 1.0. My criteria for 1.0? 100% unit test coverage, complete documentation, compatibility with 2.6+ and 3.1+ within a single package. marrow.script meets that criteria, do the others? :) - Alice. -- http://mail.python.org/mailman/listinfo/python-list
Re: Ideas for a module to process command line arguments
On Jan 11, 8:25 am, Alice Bevan–McGregor wrote: explicit callbacks or typecasting functions, etc. > > I got tired of using PasteScript and OptParse. Mostly OptParse, actually. :/ It's a pity that the argument parsing modules in the standard library are so verbose that everybody is reinventing the same thing :-( It looks like you have reinvented plac: http://pypi.python.org/pypi/plac -- http://mail.python.org/mailman/listinfo/python-list
Re: Ideas for a module to process command line arguments
On 2011-01-10 21:18:41 -0800, Sohail said: Hey, every body has their own favorite method/ways to process command line arguments. I've worked on a little CPython extension to handle command line arguments may be you'll find it interesting and useful Even I've implemented my own way to handle command-line scripts, marrow.script: https://github.com/pulp/marrow.script The idea with mine that you write a Python function... and that's it. The latest version has experimental support for class-based "subcommand" dispatch, but it needs work, needs to be updated to support sub-sub commands, and the help text generator needs to be overhauled to support classes properly. The argument list, typecasting, etc. is built from the argspec. Help text is pulled from the docstring. Decorators are provided to override short names, define explicit callbacks or typecasting functions, etc. I got tired of using PasteScript and OptParse. Mostly OptParse, actually. :/ - Alice. -- http://mail.python.org/mailman/listinfo/python-list
Re: plac, the easiest command line arguments parser in the world
On Jun 2, 12:37 am, Michele Simionato wrote: > I would like to announce to the world the first public release of > plac: > > http://pypi.python.org/pypi/plac > > Plac is a wrapper over argparse and works in all versions of > Python starting from Python 2.3 up to Python 3.1. > > With blatant immodesty, plac claims to be the easiest to use command > line arguments parser module in the Python world. Its goal is to > reduce the > learning curve of argparse from hours to minutes. It does so by > removing the need to build a command line arguments parser by hand: > actually it is smart enough to infer the parser from function > annotations. > > Here is a simple example (in Python 3) to wet your appetite: > > $ cat example.py > def main(arg: "required argument"): > "do something with arg" > print('Got %s' % arg) > > if __name__ == '__main__': > import plac; plac.call(main) # passes sys.argv[1:] to main > > $ python example.py -h > usage: example.py [-h] arg > > do something with arg > > positional arguments: > arg required argument > > optional arguments: > -h, --help show this help message and exit > > $ python example.py > usage: example.py [-h] arg > example.py: error: too few arguments > > $ python example.py arg > Got arg > > $ python example.py arg1 arg2 > usage: example.py [-h] arg > example.py: error: unrecognized arguments: arg2 > > You can find in the documentation a lot of other simple and not so > simple > examples: > > http://micheles.googlecode.com/hg/plac/doc/plac.html > > Enjoy! > > Michele Simionato > > P.S. answering an unspoken question: yes, we really needed yet > another > command line arguments parser! ;) I like this approach to command-line argument parsing! Thanks for sharing your work. -- http://mail.python.org/mailman/listinfo/python-list
Re: plac, the easiest command line arguments parser in the world
On Jun 2, 6:37 am, Michele Simionato wrote: > I would like to announce to the world the first public release of > plac: > > http://pypi.python.org/pypi/plac The second release is out. I have added the recognition of keyword arguments, improved the formatting of the help message, and added many tests. -- http://mail.python.org/mailman/listinfo/python-list
Re: plac, the easiest command line arguments parser in the world
Michele Simionato wrote: > It seems I have to take that claim back. A few hours after the > announce I was pointed out tohttp://pypi.python.org/pypi/CLIArgs > which, I must concede, is even easier to use than plac. It seems > everybody has written its own command line arguments parser! I think I still find opterator[1] to be simpler and clearer. No magic global variables, no spooky behaviour with the main function, just a decorator and docstring. 1: http://github.com/buchuki/opterator -- http://mail.python.org/mailman/listinfo/python-list
Re: plac, the easiest command line arguments parser in the world
On Jun 2, 6:37 am, Michele Simionato wrote: > With blatant immodesty, plac claims to be the easiest to use command > line arguments parser module in the Python world It seems I have to take that claim back. A few hours after the announce I was pointed out to http://pypi.python.org/pypi/CLIArgs which, I must concede, is even easier to use than plac. It seems everybody has written its own command line arguments parser! -- http://mail.python.org/mailman/listinfo/python-list
Re: plac, the easiest command line arguments parser in the world
On Jun 2, 11:01 am, Stefan Behnel wrote: > I managed to talk a Java-drilled collegue of mine into > writing a Python script for a little command line utility, but he needed a > way to organise his argument extraction code when the number of arguments > started to grow beyond two. I told him that there were two ways to do it: > do it by hand or do it right. He took the right choice and I took him to > the optparse docs, copied the first example into his code and we adapted it > a little. He just loved the beauty of it. Could you show plac to your friend? I would be curious to know what he think. Perhaps he would call out his judgment on optparse ;) -- http://mail.python.org/mailman/listinfo/python-list
Re: plac, the easiest command line arguments parser in the world
Paul Rubin, 02.06.2010 10:43: Tim Golden writes: pattern, which provides a minimally semi-self-documenting approach for positional args, but I've always found the existing offerings just a little too much work to bother with. I'll give plac a run and see how it behaves. After using optparse a couple of times I got the hang of it. Maybe its docs could be organized a bit better, but it does the obvious things conveniently once you've figured it out a bit. Same from here. I managed to talk a Java-drilled collegue of mine into writing a Python script for a little command line utility, but he needed a way to organise his argument extraction code when the number of arguments started to grow beyond two. I told him that there were two ways to do it: do it by hand or do it right. He took the right choice and I took him to the optparse docs, copied the first example into his code and we adapted it a little. He just loved the beauty of it. Stefan -- http://mail.python.org/mailman/listinfo/python-list
Re: plac, the easiest command line arguments parser in the world
Michele Simionato wrote: I would like to announce to the world the first public release of plac: http://pypi.python.org/pypi/plac Plac is a wrapper over argparse and works in all versions of Python starting from Python 2.3 up to Python 3.1. With blatant immodesty, plac claims to be the easiest to use command line arguments parser module in the Python world. Its goal is to reduce the learning curve of argparse from hours to minutes. It does so by removing the need to build a command line arguments parser by hand: actually it is smart enough to infer the parser from function annotations. Here is a simple example (in Python 3) to wet your appetite: $ cat example.py def main(arg: "required argument"): "do something with arg" print('Got %s' % arg) if __name__ == '__main__': import plac; plac.call(main) # passes sys.argv[1:] to main $ python example.py -h usage: example.py [-h] arg do something with arg positional arguments: arg required argument optional arguments: -h, --help show this help message and exit $ python example.py usage: example.py [-h] arg example.py: error: too few arguments $ python example.py arg Got arg $ python example.py arg1 arg2 usage: example.py [-h] arg example.py: error: unrecognized arguments: arg2 You can find in the documentation a lot of other simple and not so simple examples: http://micheles.googlecode.com/hg/plac/doc/plac.html Enjoy! Michele Simionato P.S. answering an unspoken question: yes, we really needed yet another command line arguments parser! ;) Thanks for participating. JM -- http://mail.python.org/mailman/listinfo/python-list
Re: plac, the easiest command line arguments parser in the world
On Jun 2, 10:43 am, Paul Rubin wrote: > Tim Golden writes: > > pattern, which provides a minimally semi-self-documenting > > approach for positional args, but I've always found the existing > > offerings just a little too much work to bother with. > > I'll give plac a run and see how it behaves. > > After using optparse a couple of times I got the hang of it. Maybe its > docs could be organized a bit better, but it does the obvious things > conveniently once you've figured it out a bit. Notice that optparse is basically useless in the use case Tim is considering (positional arguments) since it only manages options. -- http://mail.python.org/mailman/listinfo/python-list
Re: plac, the easiest command line arguments parser in the world
Tim Golden writes: > pattern, which provides a minimally semi-self-documenting > approach for positional args, but I've always found the existing > offerings just a little too much work to bother with. > I'll give plac a run and see how it behaves. After using optparse a couple of times I got the hang of it. Maybe its docs could be organized a bit better, but it does the obvious things conveniently once you've figured it out a bit. -- http://mail.python.org/mailman/listinfo/python-list
Re: plac, the easiest command line arguments parser in the world
On 02/06/2010 05:37, Michele Simionato wrote: I would like to announce to the world the first public release of plac: http://pypi.python.org/pypi/plac Plac is a wrapper over argparse and works in all versions of Python starting from Python 2.3 up to Python 3.1. I like it. I'm a constant user of the def main (a, b=1, c=2): # ... if __name__ == '__main__': main (*sys.argv[1:]) pattern, which provides a minimally semi-self-documenting approach for positional args, but I've always found the existing offerings just a little too much work to bother with. I'll give plac a run and see how it behaves. Thanks TJG -- http://mail.python.org/mailman/listinfo/python-list
plac, the easiest command line arguments parser in the world
I would like to announce to the world the first public release of plac: http://pypi.python.org/pypi/plac Plac is a wrapper over argparse and works in all versions of Python starting from Python 2.3 up to Python 3.1. With blatant immodesty, plac claims to be the easiest to use command line arguments parser module in the Python world. Its goal is to reduce the learning curve of argparse from hours to minutes. It does so by removing the need to build a command line arguments parser by hand: actually it is smart enough to infer the parser from function annotations. Here is a simple example (in Python 3) to wet your appetite: $ cat example.py def main(arg: "required argument"): "do something with arg" print('Got %s' % arg) if __name__ == '__main__': import plac; plac.call(main) # passes sys.argv[1:] to main $ python example.py -h usage: example.py [-h] arg do something with arg positional arguments: arg required argument optional arguments: -h, --help show this help message and exit $ python example.py usage: example.py [-h] arg example.py: error: too few arguments $ python example.py arg Got arg $ python example.py arg1 arg2 usage: example.py [-h] arg example.py: error: unrecognized arguments: arg2 You can find in the documentation a lot of other simple and not so simple examples: http://micheles.googlecode.com/hg/plac/doc/plac.html Enjoy! Michele Simionato P.S. answering an unspoken question: yes, we really needed yet another command line arguments parser! ;) -- http://mail.python.org/mailman/listinfo/python-list
Re: passing command line arguments to executable
On 2010-04-03 18:09, mcanjo wrote: I have an executable (I don't have access to the source code) that processes some data. I double click on the icon and a Command prompt window pops up. The program asks me for the input file, I hit enter, and then it asks me for and output filename, I hit enter a second time and it goes off and does its thing and when it is finished running the Command Prompt goes away and I have my new output file in the same directory as my executable and input file. I would like to be able to batch process a group of files. I thought about using "os.spawnv()" in a loop and at each iteration of the loop passing in the file in and out names but that didn't work. Does anyone have any ideas? It's been quite a while since I had to solve problems like the one you have. Sometimes I used a Python implementation of 'expect' successfully. -- http://mail.python.org/mailman/listinfo/python-list
Re: passing command line arguments to executable
On Apr 5, 11:22 am, mcanjo wrote: > On Apr 4, 6:32 am, Simon Brunning wrote: > > > > > On 3 April 2010 18:20, mcanjo wrote: > > > > I tried doing the following code: > > > > from subprocess import Popen > > > from subprocess import PIPE, STDOUT > > > exefile = Popen('pmm.exe', stdout = PIPE, stdin = PIPE, stderr = > > > STDOUT) > > > exefile.communicate('MarchScreen.pmm\nMarchScreen.out')[0] > > > > and the Command Prompt opened and closed, no exceptions were generated > > > but the program didn't run. Am I doing something wrong? > > > Have you tried running pmm.exe from the command line? What does that > > look like? Does it matter what the current working directory is at the > > time? > > > -- > > Cheers, > > Simon B. > > When I run the program from the command line it looks as follows: > > Enter the Input filename > (enter in filename here) > Enter the Output filename > (enter in filename here) > > If an absolute path is not specified then the output file is located > in the current working directory of the executable. The absolute path > for the output and input files may be specified also. > > Chris One thing you should do if you use pipes is to make sure you are accepting data from the program. If the program stalls because it cannot write anything to its stdout, you might have an issue. Pat -- http://mail.python.org/mailman/listinfo/python-list
Re: passing command line arguments to executable
On Apr 4, 6:32 am, Simon Brunning wrote: > On 3 April 2010 18:20, mcanjo wrote: > > > I tried doing the following code: > > > from subprocess import Popen > > from subprocess import PIPE, STDOUT > > exefile = Popen('pmm.exe', stdout = PIPE, stdin = PIPE, stderr = > > STDOUT) > > exefile.communicate('MarchScreen.pmm\nMarchScreen.out')[0] > > > and the Command Prompt opened and closed, no exceptions were generated > > but the program didn't run. Am I doing something wrong? > > Have you tried running pmm.exe from the command line? What does that > look like? Does it matter what the current working directory is at the > time? > > -- > Cheers, > Simon B. When I run the program from the command line it looks as follows: Enter the Input filename (enter in filename here) Enter the Output filename (enter in filename here) If an absolute path is not specified then the output file is located in the current working directory of the executable. The absolute path for the output and input files may be specified also. Chris -- http://mail.python.org/mailman/listinfo/python-list
Re: passing command line arguments to executable
On 4/3/10 12:09 PM, mcanjo wrote: I have an executable (I don't have access to the source code) that processes some data. I double click on the icon and a Command prompt window pops up. The program asks me for the input file, I hit enter, and then it asks me for and output filename, I hit enter a second time and it goes off and does its thing and when it is finished running the Command Prompt goes away and I have my new output file in the same directory as my executable and input file. I would like to be able to batch process a group of files. I thought about using "os.spawnv()" in a loop and at each iteration of the loop passing in the file in and out names but that didn't work. Does anyone have any ideas? I've done this a couple times on Windows. There are a few ways to do it, but I've found the easiest way is to use subprocess.check_call(). If you need to build the call with variables I find it cleaner to build the string before calling check_call(). Below is an example. callString = 'program.exe -x ' + variable returnMessage = subprocess.check_call(callString, shell=True) This works for programs that take arguments, I don't know how it will work with the program you have that asks for input in an interactive way. Does it accept arguments when you first run it? Not sure how to do it otherwise. -Josh B. -- http://mail.python.org/mailman/listinfo/python-list
Re: passing command line arguments to executable
On 4 abr, 06:17, Francesco Bochicchio wrote: > On 3 Apr, 19:20, mcanjo wrote: > > On Apr 3, 11:15 am, Patrick Maupin wrote: > > > On Apr 3, 11:09 am, mcanjo wrote: > > > > > I have an executable (I don't have access to the source code) that > > > > processes some data. I double click on the icon and a Command prompt > > > > window pops up. The program asks me for the input file, I hit enter, > > > > and then it asks me for and output filename, I hit enter a second time ^ > > > > and it goes off and does its thing and when it is finished ... > > > > You need to look at the subprocess module, and use pipes. > > > I tried doing the following code: > > > from subprocess import Popen > > from subprocess import PIPE, STDOUT > > exefile = Popen('pmm.exe', stdout = PIPE, stdin = PIPE, stderr = > > STDOUT) > > exefile.communicate('MarchScreen.pmm\nMarchScreen.out')[0] > > > and the Command Prompt opened and closed, no exceptions were generated > > but the program didn't run. Am I doing something wrong? > > I would try a couple of things (never done what you are trying to do, > so my suggestions may be useless ): > 1. use shell=True as parameter of Popen > 2. capture the output of communicate method, which returns whatever > the process emits on standard output and standard error: there could > be some message that give you hints about the solution. To mcanjo: note that you didn't provide the second '\n' Also, are you sure the program does not accept command line arguments? Many do, and switch to interactive mode when no argument is provided. I'd try with -h /h --help /help -? /? -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: passing command line arguments to executable
On 3 April 2010 18:20, mcanjo wrote: > I tried doing the following code: > > from subprocess import Popen > from subprocess import PIPE, STDOUT > exefile = Popen('pmm.exe', stdout = PIPE, stdin = PIPE, stderr = > STDOUT) > exefile.communicate('MarchScreen.pmm\nMarchScreen.out')[0] > > and the Command Prompt opened and closed, no exceptions were generated > but the program didn't run. Am I doing something wrong? Have you tried running pmm.exe from the command line? What does that look like? Does it matter what the current working directory is at the time? -- Cheers, Simon B. -- http://mail.python.org/mailman/listinfo/python-list
Re: passing command line arguments to executable
On 3 Apr, 19:20, mcanjo wrote: > On Apr 3, 11:15 am, Patrick Maupin wrote: > > > > > On Apr 3, 11:09 am, mcanjo wrote: > > > > I have an executable (I don't have access to the source code) that > > > processes some data. I double click on the icon and a Command prompt > > > window pops up. The program asks me for the input file, I hit enter, > > > and then it asks me for and output filename, I hit enter a second time > > > and it goes off and does its thing and when it is finished running the > > > Command Prompt goes away and I have my new output file in the same > > > directory as my executable and input file. I would like to be able to > > > batch process a group of files. I thought about using "os.spawnv()" in > > > a loop and at each iteration of the loop passing in the file in and > > > out names but that didn't work. Does anyone have any ideas? > > > You need to look at the subprocess module, and use pipes. > > > Regards, > > Pat > > I tried doing the following code: > > from subprocess import Popen > from subprocess import PIPE, STDOUT > exefile = Popen('pmm.exe', stdout = PIPE, stdin = PIPE, stderr = > STDOUT) > exefile.communicate('MarchScreen.pmm\nMarchScreen.out')[0] > > and the Command Prompt opened and closed, no exceptions were generated > but the program didn't run. Am I doing something wrong? I would try a couple of things (never done what you are trying to do, so my suggestions may be useless ): 1. use shell=True as parameter of Popen 2. capture the output of communicate method, which returns whatever the process emits on standard output and standard error: there could be some message that give you hints about the solution. Ciao -- FB -- http://mail.python.org/mailman/listinfo/python-list
Re: passing command line arguments to executable
On Apr 3, 12:20 pm, mcanjo wrote: > On Apr 3, 11:15 am, Patrick Maupin wrote: > > > > > On Apr 3, 11:09 am, mcanjo wrote: > > > > I have an executable (I don't have access to the source code) that > > > processes some data. I double click on the icon and a Command prompt > > > window pops up. The program asks me for the input file, I hit enter, > > > and then it asks me for and output filename, I hit enter a second time > > > and it goes off and does its thing and when it is finished running the > > > Command Prompt goes away and I have my new output file in the same > > > directory as my executable and input file. I would like to be able to > > > batch process a group of files. I thought about using "os.spawnv()" in > > > a loop and at each iteration of the loop passing in the file in and > > > out names but that didn't work. Does anyone have any ideas? > > > You need to look at the subprocess module, and use pipes. > > > Regards, > > Pat > > I tried doing the following code: > > from subprocess import Popen > from subprocess import PIPE, STDOUT > exefile = Popen('pmm.exe', stdout = PIPE, stdin = PIPE, stderr = > STDOUT) > exefile.communicate('MarchScreen.pmm\nMarchScreen.out')[0] > > and the Command Prompt opened and closed, no exceptions were generated > but the program didn't run. Am I doing something wrong? I don't use communicate because I've never gotten it to do what I want. I also don't use Windows. I have a linux solution that allows me to feed stuf into a pipe, but I don't think it will work under Windows because it uses os functions to block on empty pipes that Windows doesn't support. You might read PEP 3145 -- it addresses some of the issues, and there is some code to help, I think: http://www.python.org/dev/peps/pep-3145/ Regards, Pat -- http://mail.python.org/mailman/listinfo/python-list
Re: passing command line arguments to executable
On Apr 3, 11:15 am, Patrick Maupin wrote: > On Apr 3, 11:09 am, mcanjo wrote: > > > I have an executable (I don't have access to the source code) that > > processes some data. I double click on the icon and a Command prompt > > window pops up. The program asks me for the input file, I hit enter, > > and then it asks me for and output filename, I hit enter a second time > > and it goes off and does its thing and when it is finished running the > > Command Prompt goes away and I have my new output file in the same > > directory as my executable and input file. I would like to be able to > > batch process a group of files. I thought about using "os.spawnv()" in > > a loop and at each iteration of the loop passing in the file in and > > out names but that didn't work. Does anyone have any ideas? > > You need to look at the subprocess module, and use pipes. > > Regards, > Pat I tried doing the following code: from subprocess import Popen from subprocess import PIPE, STDOUT exefile = Popen('pmm.exe', stdout = PIPE, stdin = PIPE, stderr = STDOUT) exefile.communicate('MarchScreen.pmm\nMarchScreen.out')[0] and the Command Prompt opened and closed, no exceptions were generated but the program didn't run. Am I doing something wrong? -- http://mail.python.org/mailman/listinfo/python-list
Re: passing command line arguments to executable
On 3 April 2010 17:09, mcanjo wrote: > I have an executable (I don't have access to the source code) that > processes some data. I double click on the icon and a Command prompt > window pops up. The program asks me for the input file, I hit enter, > and then it asks me for and output filename, I hit enter a second time > and it goes off and does its thing and when it is finished running the > Command Prompt goes away and I have my new output file in the same > directory as my executable and input file. I would like to be able to > batch process a group of files. I thought about using "os.spawnv()" in > a loop and at each iteration of the loop passing in the file in and > out names but that didn't work. Does anyone have any ideas? Have a look at the subprocess module. -- Cheers, Simon B. -- http://mail.python.org/mailman/listinfo/python-list
Re: passing command line arguments to executable
On Apr 3, 11:09 am, mcanjo wrote: > I have an executable (I don't have access to the source code) that > processes some data. I double click on the icon and a Command prompt > window pops up. The program asks me for the input file, I hit enter, > and then it asks me for and output filename, I hit enter a second time > and it goes off and does its thing and when it is finished running the > Command Prompt goes away and I have my new output file in the same > directory as my executable and input file. I would like to be able to > batch process a group of files. I thought about using "os.spawnv()" in > a loop and at each iteration of the loop passing in the file in and > out names but that didn't work. Does anyone have any ideas? You need to look at the subprocess module, and use pipes. Regards, Pat -- http://mail.python.org/mailman/listinfo/python-list
passing command line arguments to executable
I have an executable (I don't have access to the source code) that processes some data. I double click on the icon and a Command prompt window pops up. The program asks me for the input file, I hit enter, and then it asks me for and output filename, I hit enter a second time and it goes off and does its thing and when it is finished running the Command Prompt goes away and I have my new output file in the same directory as my executable and input file. I would like to be able to batch process a group of files. I thought about using "os.spawnv()" in a loop and at each iteration of the loop passing in the file in and out names but that didn't work. Does anyone have any ideas? -- http://mail.python.org/mailman/listinfo/python-list
Re: How to pass Chinese characters as command-line arguments?
In <7slr5ife6...@mid.uni-berlin.de> "Diez B. Roggisch" writes: >Am 31.01.10 16:52, schrieb kj: >> I want to pass Chinese characters as command-line arguments to a >> Python script. My terminal has no problem displaying these >> characters, and passing them to the script, but I can't get Python >> to understand them properly. >> >> E.g. if I pass one such character to the simple script >> >> import sys >> print sys.argv[1] >> print type(sys.argv[1]) >> >> the first line of the output looks fine (identical to the input), >> but the second line says "". If I add the line >> >> arg = unicode(sys.argv[1]) >> >> I get the error >> >> Traceback (most recent call last): >>File "kgrep.py", line 4, in >> arg = unicode(sys.argv[1]) >> UnicodeDecodeError: 'ascii' codec can't decode byte 0xe8 in position 0: >> ordinal not in range(128) >> >> What must I do to get Python to recognize command-line arguments >> as utf-8 Unicode? >The last sentence reveals your problem: utf-8 is *not* unicode. It's an >encoding of unicode, which is a crucial difference. > From the outside you get byte-streams, and if these happen to be >encoded in utf-8, you can simply decode them: >arg = unicode(sys.argv[1], "utf-8") Thanks! kynn -- http://mail.python.org/mailman/listinfo/python-list
Re: How to pass Chinese characters as command-line arguments?
Am 31.01.10 16:52, schrieb kj: I want to pass Chinese characters as command-line arguments to a Python script. My terminal has no problem displaying these characters, and passing them to the script, but I can't get Python to understand them properly. E.g. if I pass one such character to the simple script import sys print sys.argv[1] print type(sys.argv[1]) the first line of the output looks fine (identical to the input), but the second line says "". If I add the line arg = unicode(sys.argv[1]) I get the error Traceback (most recent call last): File "kgrep.py", line 4, in arg = unicode(sys.argv[1]) UnicodeDecodeError: 'ascii' codec can't decode byte 0xe8 in position 0: ordinal not in range(128) What must I do to get Python to recognize command-line arguments as utf-8 Unicode? The last sentence reveals your problem: utf-8 is *not* unicode. It's an encoding of unicode, which is a crucial difference. From the outside you get byte-streams, and if these happen to be encoded in utf-8, you can simply decode them: arg = unicode(sys.argv[1], "utf-8") Diez -- http://mail.python.org/mailman/listinfo/python-list
How to pass Chinese characters as command-line arguments?
I want to pass Chinese characters as command-line arguments to a Python script. My terminal has no problem displaying these characters, and passing them to the script, but I can't get Python to understand them properly. E.g. if I pass one such character to the simple script import sys print sys.argv[1] print type(sys.argv[1]) the first line of the output looks fine (identical to the input), but the second line says "". If I add the line arg = unicode(sys.argv[1]) I get the error Traceback (most recent call last): File "kgrep.py", line 4, in arg = unicode(sys.argv[1]) UnicodeDecodeError: 'ascii' codec can't decode byte 0xe8 in position 0: ordinal not in range(128) What must I do to get Python to recognize command-line arguments as utf-8 Unicode? FWIW, my os is Darwin, my shell (zsh) runs on Terminal, and none of my locale (LC_*) variables is set. TIA! kynn -- http://mail.python.org/mailman/listinfo/python-list
Re: Command line arguments??
On Tue, 17 Nov 2009 23:57:55 +, Rhodri James wrote: >>> Quote the filenames or escape the spaces: >>> >>> C:\Python26\Python.exe C:\echo.py "C:\New Folder\text.txt" >>> >>> We've been living with this pain ever since windowed GUIs encouraged >>> users >>> to put spaces in their file names (Apple, I'm looking at you!). >>> Fundamentally, if people want the pretty they have to live with the >>> consequences. >> >> We've been living with much worse ever since Unix allowed users to put >> not only spaces but even newlines in their filenames. > > You'll notice I said "encouraged", not "allowed". You'll notice I said "allowed", not "encouraged". Code which can't handle spaces in filenames is broken from the outset; it doesn't suddenly break the first time that someone passes a filename containing spaces. I have a suspicion that Win95 put spaces in two of the most important directory names specifically to force developers to deal with this. Nowadays, any Windows program which cannot handle spaces in pathnames is usually a port of a Unix program (and a shoddy one at that). OTOH, I'm surprised at how much Windows software still cannot handle filenames outside of the system codepage (i.e. it's using the byte-oriented API rather than the Unicode API). -- http://mail.python.org/mailman/listinfo/python-list
Re: Command line arguments??
Rhodri James wrote: We've been living with this pain ever since windowed GUIs encouraged users to put spaces in their file names (Apple, I'm looking at you!). It's not really Apple's fault. There was no problem with spaces in filenames in the classic MacOS environment, because there was no textual command language (at least not one that people used in day-to-day work). There's a slight problem sometimes in MacOSX when you use the shell, but at least unix passes args to a program as separate strings, so as long as you exec() something directly and avoid the shell, you're safe. Windows, on the other hand, passes all the args as a single string, whether a shell is involved or not (due to blindly adopting CP/M's argument passing mechanism into MSDOS). Microsoft screwed up by trying to partially implement Apple's ideas on top of a system that wasn't engineered to cope with them. -- Greg -- http://mail.python.org/mailman/listinfo/python-list
Re: Command line arguments??
Nobody wrote: On Tue, 17 Nov 2009 11:47:46 -0800, Gerry wrote: How about this: lastarg = " ".join(sys.argv[2:]) What about it? IOW, why would you want to do that? Like many tricks, it'd work if several conditions applied: 1) there's exactly two arguments expected on the command line 2) you know that the second argument may have one or more spaces in it, but not consecutively, and no quotes immediately after any such space. 3) you don't mind fooling the user by making *most* cases work, so he's not trained for the general case. This one reminds me of CreateProcess() in Windows, which parses for the program by looking for each space, and seeing if there's an appropriate EXE file there. So if you have stuff installed in "C:\Program Files\My Dir\yyy" directory, you can be blindsided by someone creating a program in the root called c:\program.exe, or "c:\Program Files\My.exe" CreateProcess() keeps trying till one works, instead of immediately giving a diagnosable error. That was my (correct) diagnosis of an actual customer problem, referred to me by tech support. Customer described error message, and I studied what could cause it. Called back and asked whether there was a program.exe in the root directory. Told him to (temporarily) remove it. Problem vanished. Customer astounded how we could know about its existence. Of course it was really a bug in one of the products at my company, where quotes weren't used. Not usually needed, because of this "flexibility" on the part of CreateProcess() DaveA -- http://mail.python.org/mailman/listinfo/python-list
Re: Command line arguments??
On Tue, 17 Nov 2009 19:26:46 -, Nobody wrote: On Mon, 16 Nov 2009 23:30:09 +, Rhodri James wrote: Quote the filenames or escape the spaces: C:\Python26\Python.exe C:\echo.py "C:\New Folder\text.txt" We've been living with this pain ever since windowed GUIs encouraged users to put spaces in their file names (Apple, I'm looking at you!). Fundamentally, if people want the pretty they have to live with the consequences. We've been living with much worse ever since Unix allowed users to put not only spaces but even newlines in their filenames. You'll notice I said "encouraged", not "allowed". -- Rhodri James *-* Wildebeest Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: Command line arguments??
On Tue, 17 Nov 2009 11:47:46 -0800, Gerry wrote: > How about this: > > lastarg = " ".join(sys.argv[2:]) What about it? IOW, why would you want to do that? -- http://mail.python.org/mailman/listinfo/python-list
Re: Command line arguments??
On Nov 17, 2:26 pm, Nobody wrote: > On Mon, 16 Nov 2009 23:30:09 +, Rhodri James wrote: > > Quote the filenames or escape the spaces: > > > C:\Python26\Python.exe C:\echo.py "C:\New Folder\text.txt" > > > We've been living with this pain ever since windowed GUIs encouraged users > > to put spaces in their file names (Apple, I'm looking at you!). > > Fundamentally, if people want the pretty they have to live with the > > consequences. > > We've been living with much worse ever since Unix allowed users to put > not only spaces but even newlines in their filenames. > > At least, those of us who prefer "works" over "sort of works most of the > time" have. > > Then Python 3 decides to pretend that argv and environ and stdin contain > text rather than bytes, thereby ensuring that Python 2 will outlive Python > 3. How about this: lastarg = " ".join(sys.argv[2:]) -- http://mail.python.org/mailman/listinfo/python-list
Re: Command line arguments??
On Mon, 16 Nov 2009 23:30:09 +, Rhodri James wrote: > Quote the filenames or escape the spaces: > > C:\Python26\Python.exe C:\echo.py "C:\New Folder\text.txt" > > We've been living with this pain ever since windowed GUIs encouraged users > to put spaces in their file names (Apple, I'm looking at you!). > Fundamentally, if people want the pretty they have to live with the > consequences. We've been living with much worse ever since Unix allowed users to put not only spaces but even newlines in their filenames. At least, those of us who prefer "works" over "sort of works most of the time" have. Then Python 3 decides to pretend that argv and environ and stdin contain text rather than bytes, thereby ensuring that Python 2 will outlive Python 3. -- http://mail.python.org/mailman/listinfo/python-list
Re: Command line arguments??
On Nov 16, 5:30 pm, "Rhodri James" wrote: > We've been living with this pain ever since windowed GUIs encouraged users > to put spaces in their file names (Apple, I'm looking at you!). > Fundamentally, if people want the pretty they have to live with the > consequences. Thanks everyone , problem solved! -- http://mail.python.org/mailman/listinfo/python-list
Re: Command line arguments??
On Mon, 16 Nov 2009 23:18:23 -, rantingrick wrote: I am currently having "fun" with command line arguments in a windows environment. If i get a path that has spaces anywhere in it my script gets the wrong arguments from sys.argv. You guy's probably know what i am talking about. Heres and example. 'C:\\Python26\\Python.exe C:\\echo.py C:\\New Folder\\text.txt' inside my script i get the following result from sys.argv ['C:\\Python26\\Python.exe', 'C:\\echo.py', 'C:\\New', 'Folder\ \text.txt'] So i've got a few options 1. have people replace every space in all file paths system wide (sucks) 2. Create a custom parser, join the argv list, parse it...(maybe) 3. please tell me there is an option 3? (hopefully) Quote the filenames or escape the spaces: C:\Python26\Python.exe C:\echo.py "C:\New Folder\text.txt" We've been living with this pain ever since windowed GUIs encouraged users to put spaces in their file names (Apple, I'm looking at you!). Fundamentally, if people want the pretty they have to live with the consequences. -- Rhodri James *-* Wildebeest Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: Command line arguments??
On Mon, Nov 16, 2009 at 6:18 PM, rantingrick wrote: > I am currently having "fun" with command line arguments in a windows > environment. If i get a path that has spaces anywhere in it my script > gets the wrong arguments from sys.argv. You guy's probably know what i > am talking about. Heres and example. > > 'C:\\Python26\\Python.exe C:\\echo.py C:\\New Folder\\text.txt' > > inside my script i get the following result from sys.argv > > ['C:\\Python26\\Python.exe', 'C:\\echo.py', 'C:\\New', 'Folder\ > \text.txt'] > > So i've got a few options > 1. have people replace every space in all file paths system wide > (sucks) > 2. Create a custom parser, join the argv list, parse it...(maybe) > 3. please tell me there is an option 3? (hopefully) > -- > http://mail.python.org/mailman/listinfo/python-list > The same thing you have to do with every command line program - wrap it in quotes. C:\\Python26\\python.exe C:\\echo.py "C:\\New Folder\\text.txt" -- http://mail.python.org/mailman/listinfo/python-list
Command line arguments??
I am currently having "fun" with command line arguments in a windows environment. If i get a path that has spaces anywhere in it my script gets the wrong arguments from sys.argv. You guy's probably know what i am talking about. Heres and example. 'C:\\Python26\\Python.exe C:\\echo.py C:\\New Folder\\text.txt' inside my script i get the following result from sys.argv ['C:\\Python26\\Python.exe', 'C:\\echo.py', 'C:\\New', 'Folder\ \text.txt'] So i've got a few options 1. have people replace every space in all file paths system wide (sucks) 2. Create a custom parser, join the argv list, parse it...(maybe) 3. please tell me there is an option 3? (hopefully) -- http://mail.python.org/mailman/listinfo/python-list
Re: Raw command line arguments
En Fri, 24 Apr 2009 06:40:23 -0300, Enchanter escribió: How to pass the raw command line arguments to the python? That depends on the OS or the shell you're using. Such as: mypython.py txt -c "Test Only" {Help} The arguments I hope to get is: txt -c "Test Only" {Help} -- Keep the quotation marks in the arguments. I guess you're using Windows: gg>type show.py import sys print sys.argv gg>python show.py one txt -c """Test Only""" {Help} ['show.py', 'one', 'txt', '-c', '"Test Only"', '{Help}'] Two double quotes represent a single one. And you have to enclose the whole argument in quotes too because of the space character. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Raw command line arguments
Enchanter wrote: How to pass the raw command line arguments to the python? Such as: mypython.py txt -c "Test Only" {Help} The arguments I hope to get is: txt -c "Test Only" {Help} -- Keep the quotation marks in the arguments. As Chris has said, the shell (and the C runtime) preprocesses the line before python ever sees it. However, if you're on Windows, there is a function GetCommandLine, located in Kernel32.dll, which I *think* keeps the raw bytes typed by the user. Clearly, that would be a non-portable answer, but here's some samples if you want to try it: import sys print sys.argv#this one loses the quotes import ctypes #print ctypes.windll.kernel32.GetModuleHandleA #hdl = ctypes.windll.kernel32.GetModuleHandleA(0) #print hdl func = ctypes.windll.kernel32.GetCommandLineA print func func.restype = ctypes.c_char_p cmd = ctypes.windll.kernel32.GetCommandLineA() print cmd #this one gives a single string, such as the one below: "C:\ProgFiles\Python26\python.exe" "M:\Programming\Python\sources\dummy\args.py" txt -c "Test Only" (Help) If you do go this route, but still want to be portable, you could make this code conditional on platform, then document the user to use escaping on Linux and Apple, while you do this approach for Windows. -- http://mail.python.org/mailman/listinfo/python-list
Re: Raw command line arguments
On Fri, Apr 24, 2009 at 2:40 AM, Enchanter wrote: > How to pass the raw command line arguments to the python? > > Such as: > > mypython.py txt -c "Test Only" {Help} > > > The arguments I hope to get is: > > txt -c "Test Only" {Help} -- Keep the > quotation marks in the arguments. Remember that the quotes are parsed by the shell before python ever receives the arguments, so you have to deal with it in whatever is calling python. Recall/note the differences between: rm foo bar #delete foo and delete bar rm "foo bar" #delete one file with a space in its name but no quotes in its name rm 'foo"bar"baz' #delete one file with double-quotes in its name rm "foo\"bar\"baz" #delete the same file as in the previous example Therefore, you need to invoke the script differently to take account of the shell's quote processing by adding another set of quotes, like so: mypython.py txt -c '"Test Only"' {Help} #or alternatively: mypython.py txt -c "\"Test Only\"" {Help} Cheers, Chris -- I have a blog: http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Raw command line arguments
How to pass the raw command line arguments to the python? Such as: mypython.py txt -c "Test Only" {Help} The arguments I hope to get is: txt -c "Test Only" {Help} -- Keep the quotation marks in the arguments. -- http://mail.python.org/mailman/listinfo/python-list
Taking command line arguments from another program
Hello folks ,I have a program in which a text file is generated as an output eg C:\prog\ prog -x test.txt Right now whenever i have to read the test file i have to put its name manually in my code. eg f=open("c:\\prog\\test.txt","r") How ever i want to add the name of the test file dynamically to my program ie , if every time i give C:\prog\ prog -x test.txt The filename (test.txt) automatically comes in f=open("c:\\prog\\test.txt","r") C:\prog\ prog -x file1.txt f=open("c:\\prog\\file1","r") in other words i do not want to do hard code the name of the file in my code every time i need to read it. I was reading about the sys module and i guess sys.argv would take the input from the command line whenever i run the python script . Please guide me in the right direction on how to tackle the problem. Thanks in advance Aditya -- http://mail.python.org/mailman/listinfo/python-list
Re: Angle brackets in command-line arguments?
On Jul 16, 11:16 am, Gary Herron <[EMAIL PROTECTED]> wrote: > Keith Hughitt wrote: > > Hi all, > > > I am using someone else's script which expects input in the form of: > > > ./script.py arg2 > > > I was wondering if the angle-brackets here have a special meaning? It > > seems like > > they specify an input and output stream to use in place of the > > console. I could not > > find anything in the python manual or Python in a Nut-shell though. > > > Anyone know? > > > Thanks, > > Keith > > -- > >http://mail.python.org/mailman/listinfo/python-list > > In most Unix/Linux and related OS shells, the angled brackets *do* > specify input and output streams as you surmise. However, they are > *not* seen by the script as command line arguments. (And they are > *not* brackets, and do not need to be matched. ) > > For any command, > cmd < file > redirects the contents of file to cmd's standard input, which in Python > is accessed by reading from sys.stdin (use input or raw_input or > sys.stdin.read...) > > Also for any command, > cmd > file > redirects the output of cmd to the named file. In Python this can be > accessed using print, sys.stdout.write, ... > > Anything written to sys.stderr will not be caught by the ">" > redirection, ans so will probably end up on the screen instead of in file. > > Also various shells will provide similar functionality using a variety > of similar syntaxes: <<, >>, >&, and |, and so on. > > Gary Herron Thanks all for the quick response. I should have known it was shell- related. I haven't ever had to use this kind of redirection before, mostly just the single-bracket version to feed the contents of a file into some command. The reason it was causing me concern in the first place was that I was trying to execute a python script from Apache Ant, and it was failing. It turned out that when I escaped the angle brackets in Ant, they were there-after treated as normal command-line arguments, so when the script was then executed, it just had some additional values in sys.argv. I ended up getting around the issue by creating a small bash-script which simply wraps input in angle brackets and then executes the python script itself. That way I didn't have to escape anything in in Ant, and things worked well. Thanks everyone for taking the time to explain things to me. I really appreciate the help :) Take care, Keith -- http://mail.python.org/mailman/listinfo/python-list
Re: Angle brackets in command-line arguments?
Keith Hughitt wrote: Hi all, I am using someone else's script which expects input in the form of: ./script.py arg2 I was wondering if the angle-brackets here have a special meaning? It seems like they specify an input and output stream to use in place of the console. I could not find anything in the python manual or Python in a Nut-shell though. Anyone know? Thanks, Keith -- http://mail.python.org/mailman/listinfo/python-list In most Unix/Linux and related OS shells, the angled brackets *do* specify input and output streams as you surmise. However, they are *not* seen by the script as command line arguments. (And they are *not* brackets, and do not need to be matched. ) For any command, cmd < file redirects the contents of file to cmd's standard input, which in Python is accessed by reading from sys.stdin (use input or raw_input or sys.stdin.read...) Also for any command, cmd > file redirects the output of cmd to the named file. In Python this can be accessed using print, sys.stdout.write, ... Anything written to sys.stderr will not be caught by the ">" redirection, ans so will probably end up on the screen instead of in file. Also various shells will provide similar functionality using a variety of similar syntaxes: <<, >>, >&, and |, and so on. Gary Herron -- http://mail.python.org/mailman/listinfo/python-list