Question About Command line arguments

Benjamin Kaplan benjamin.kaplan at case.edu
Fri Jun 10 15:42:57 EDT 2011


On Jun 10, 2011 10:26 AM, "Mark Phillips" <mark at phillipsmarketing.biz>
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
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20110610/fdb3d38c/attachment-0001.html>


More information about the Python-list mailing list