passing argument to script

Daniel Nogradi nogradi at gmail.com
Fri Apr 7 07:08:50 EDT 2006


> hi
>
> if i have a string like this
>
> "ABCE-123456  ABC_DEF_Suggest(abc def ghi).txt"
>
> that needs to be passed to a python script
> and i wanted to get the words inside the brackets after i passed this
> string. I did a re
> something like
>
> thestring = sys.argv[1:]
> pat = re.compile(r".*\((.*)\)\.txt$")
> if pat.search(thestring):
>    words = pat.search(thestring).group(1)
>
> but it doesn't return anything for words variable.
> When i specifically define the string inside the python script , it
> works
>
> thestring = "ABCE-123456  ABC_DEF_Suggest(abc def ghi).txt"
>
> I also tried str(thestring) but also did not work
> what is wrong with the argument passing?

Are you doing this on Linux or Windows?

If you execute your script from the command line on Linux you need to
enclose it in quotation marks otherwise your shell will interfere. So
you need to invoke your program as

python yourscript.py "ABCE-123456  ABC_DEF_Suggest(abc def ghi).txt"

and need to refer to the argument as sys.argv[1:][0], so yourscript.py should be

import sys, re
thestring = sys.argv[1:][0]
pat = re.compile(r".*\((.*)\)\.txt$")
if pat.search(thestring):
       words = pat.search(thestring).group(1)
       print words

I'm not sure what you need to do on Windows though.



More information about the Python-list mailing list