[Tutor] ArgumentParser - Command Line arguments
Asad
asad.hasan2004 at gmail.com
Thu Nov 21 03:33:12 EST 2019
Hi All ,,
I have python 2.6.4 on solaris therefore I am not able to use the argparse .
The reason behind using argparse was to capture exception and print the
statements within the except block .
So here is the logic
if len(sys.argv) == 3:
first = sys.argv[1]
second = sys.argv[2]
else:
print "enter the file1 and file2 or file3"
if re.search("errr_pattern", file1):
try :
with open (file2,'r') as f4 :
print "Hi hello"
except TyeError :
print " Hi"
so this works fine if i use python script.py file1 file2 ==> It gives the
required results (hi Hello)
if I use python script.py file1 it errors out :
print("first:", file1)
NameError: name 'file1' is not defined
Instead I want it to print "hi" actually whatever statements are in except
block .
If I use this :
python script.py file1 file2
parser = argparse.ArgumentParser()
parser.add_argument("first", type = str, help = 'Input for
sqlinvocation.log')
parser.add_argument("second", nargs="?")
args = parser.parse_args()
if len(sys.argv) == 3:
args.first = sys.argv[1]
args.second = sys.argv[2]
else:
print "enter the file1 and file2 or file3"
It works as expected but unfortunately I cannot use argparse
I was looked for alternative :from optparse import OptionParser
was unable to get sucess ,
Please advice and recommend,
Thanks,
On Wed, Nov 20, 2019 at 5:52 PM Asad <asad.hasan2004 at gmail.com> wrote:
> Hi All ,
>
> Need advice or code how to proceed . I am executing python
> script as .
>
> python script.py file1 file2
>
> parser = argparse.ArgumentParser()
> parser.add_argument("first", type = str, help = 'Input for
> sqlinvocation.log')
> parser.add_argument("second", nargs="?")
>
> args = parser.parse_args()
>
> if len(sys.argv) == 3:
> args.first = sys.argv[1]
> args.second = sys.argv[2]
>
> else:
>
> print "enter the sqlinvocation log and qopatch or
> sqlpatch_catcon_0.log"
>
> print("first:", args.first)
> print("second:", args.second)
>
>
>
>
> If I execute python script.py file1 file2 1.
>
> It gives the following error :
>
> error: unrecognized arguments: 1
>
> I few questions . How can perform the following :
>
> 1) How can the python script process file1 and file2 and run the script
> with those command line arguments and drop 1 and other inputs if provided
> by user.
>
> 2)How can the script to consider always file1 as args.first even if the
> command is executed as :
>
> python script.py file3 file1
>
> Somehow if its find the file1 in the list of arguments it should consider
> as args.first and the other file as args.second
>
>
> Thanks,
>
>
>
> --
> Asad Hasan
> +91 9582111698
>
--
Asad Hasan
+91 9582111698
More information about the Tutor
mailing list