[Tutor] python-files

Asad asad.hasan2004 at gmail.com
Sun Jan 27 09:57:16 EST 2019


Hi All ,

          I tried the following code  :

parser = argparse.ArgumentParser()
parser.add_argument("first")
parser.add_argument("second", nargs="?")
args = parser.parse_args()
print("first:", args.first)

print("second:", args.second)

When I execute the script it gives error :

python python_json_20001_oratest_v1.py "file1"
('first:', 'file1')
('second:', None)
Traceback (most recent call last):
  File "test.py", line 211, in <module>
    with open(args.second, 'r') as f :
TypeError: coercing to Unicode: need string or buffer, NoneType found


if I see in line number 211 it with open(args.second, 'r') as f :

try :
        with open(args.second, 'r') as f :
             for line in f:
                print line
except IOError:
         print "The default error is err-1 because file2 was not provided "

Does that mean my try and except block is not working because if
args.second  is None as in this case then it should print "The default
error is err-1 because file2 was not provided "

Please advice ,

Thanks,


> ---------- Forwarded message ----------
> From: Peter Otten <__peter__ at web.de>
> To: tutor at python.org
> Cc:
> Bcc:
> Date: Sun, 27 Jan 2019 10:30:12 +0100
> Subject: Re: [Tutor] python - files
> Cameron Simpson wrote:
>
> > Mats has mentioned the modules getopt and argparse etc. These are
> > primarily aimed at option parsing ("-v", "-o foo"). Your situation
> > occurs _after_ the option parsing (in your case, there are no options).
>
> Not argparse. The main advantage over optparse is its handling of
> positional
> arguments. Your custom logic
>
> >   def main(argv):
> >     cmd = argv.pop(0)   # collect the command word
> >     badopts = False
> >     # mandatory first argument
> >     if not argv:
> >       print("%s: missing first argument" % cmd, file=sys.stderr)
> >       badopts = True
> >     else:
> >       first = argv.pop(0)
> >       # optional second argument
> >       if argv:
> >         second = argv.pop(0)    # explicit argument 2, use it
> >       else:
> >         second = None           # or some otherdefault
> >       if argv:
> >         print("%s: extra arguments: %r" % (cmd, argv), file=sys.stderr)
> >         badopts = true
> >     if badopts:
> >       print("%s: invalid invocation, aborting" % cmd, file=sys.stderr)
> >       return 2
> >     ... work with first and second ...
>
> can roughly be replicated with the two lines
>
> parser.add_argument("first")
> parser.add_argument("second", nargs="?")
>
> A working script:
>
> $ cat test.py
> #!/usr/bin/python3
> import argparse
>
> def main():
>     parser = argparse.ArgumentParser()
>
>     parser.add_argument("first")
>     parser.add_argument("second", nargs="?")
>
>     args = parser.parse_args()
>
>     print("first:", args.first)
>     print("second:", args.second)
>
> if __name__ == "__main__":
>     main()
>
> $ ./test.py
> usage: test.py [-h] first [second]
> test.py: error: the following arguments are required: first
>
> $ ./test.py -h
> usage: test.py [-h] first [second]
>
> positional arguments:
>   first
>   second
>
> optional arguments:
>   -h, --help  show this help message and exit
>
> $ ./test.py ONE
> first: ONE
> second: None
>
> $ ./test.py ONE TWO
> first: ONE
> second: TWO
>
> $ ./test.py ONE TWO THREE
> usage: test.py [-h] first [second]
> test.py: error: unrecognized arguments: THREE
>
> Argparse makes a usable standard command line interface easy to set up (if
> you need non-standard behaviour it gets a bit harder).
>
> There is also a companion module argcomplete (not in the stdlib) that
> enables autocompletion.
>
>
>
>
>
>
> ---------- Forwarded message ----------
> From: Cameron Simpson <cs at cskk.id.au>
> To: tutor at python.org
> Cc:
> Bcc:
> Date: Sun, 27 Jan 2019 20:54:13 +1100
> Subject: Re: [Tutor] python - files
> On 27Jan2019 10:30, Peter Otten <__peter__ at web.de> wrote:
> >Cameron Simpson wrote:
> >> Mats has mentioned the modules getopt and argparse etc. These are
> >> primarily aimed at option parsing ("-v", "-o foo"). Your situation
> >> occurs _after_ the option parsing (in your case, there are no options).
> >
> >Not argparse. The main advantage over optparse is its handling of
> positional
> >arguments.
>
> I stand corrected.
>
> >Your custom logic
> [...]
> >can roughly be replicated with the two lines
> >
> >parser.add_argument("first")
> >parser.add_argument("second", nargs="?")
> >[... extended example ...]
>
> Thank you!
>
> Cheers,
> Cameron Simpson <cs at cskk.id.au>
>
>
>
>
> ---------- Forwarded message ----------
> From: Marco Mistroni <mmistroni at gmail.com>
> To: mhysnm1964 at gmail.com
> Cc: tutor at python.org
> Bcc:
> Date: Sun, 27 Jan 2019 10:46:06 +0000
> Subject: Re: [Tutor] Web scraping using selenium and navigating nested
> dictionaries / lists.
> Hi my 2 cents. Have a look at scrapy for scraping.selenium is v good  tool
> to learn but is mainly to automate uat of guis
> Scrapy will scrape for you and u can automate it via cron. It's same stuff
> I am doing ATM
> Hth
>
> On Sun, Jan 27, 2019, 8:34 AM <mhysnm1964 at gmail.com wrote:
>
> > All,
> >
> >
> >
> > Goal of new project.
> >
> > I want to scrape all my books from Audible.com that I have purchased.
> > Eventually I want to export this as a CSV file or maybe Json. I have not
> > got
> > that far yet. The reasoning behind this is to  learn selenium  for my
> work
> > and get the list of books I have purchased. Killing two birds with one
> > stone
> > here. The work focus is to see if selenium   can automate some of the
> > testing I have to do and collect useful information from the web page for
> > my
> > reports. This part of the goal is in the future. As I need to build my
> > python skills up.
> >
> >
> >
> > Thus far, I have been successful in logging into Audible and showing the
> > library of books. I am able to store the table of books and want to use
> > BeautifulSoup to extract the relevant information. Information I will
> want
> > from the table is:
> >
> > *       Author
> > *       Title
> > *       Date purchased
> > *       Length
> > *       Is the book in a series (there is a link for this)
> > *       Link to the page storing the publish details.
> > *       Download link
> >
> > Hopefully this has given you enough information on what I am trying to
> > achieve at this stage. AS I learn more about what I am doing, I am adding
> > possible extra's tasks. Such as verifying if I have the book already
> > download via itunes.
> >
> >
> >
> > Learning goals:
> >
> > Using the BeautifulSoup  structure that I have extracted from the page
> > source for the table. I want to navigate the tree structure.
> BeautifulSoup
> > provides children, siblings and parents methods. This is where I get
> stuck
> > with programming logic. BeautifulSoup does provide find_all method plus
> > selectors which I do not want to use for this exercise. As I want to
> learn
> > how to walk a tree starting at the root and visiting each node of the
> tree.
> > Then I can look at the attributes for the tag as I go. I believe I have
> to
> > set up a recursive loop or function call. Not sure on how to do this.
> > Pseudo
> > code:
> >
> >
> >
> > Build table structure
> >
> > Start at the root node.
> >
> > Check to see if there is any children.
> >
> > Pass first child to function.
> >
> > Print attributes for tag at this level
> >
> > In function, check for any sibling nodes.
> >
> > If exist, call function again
> >
> > If no siblings, then start at first sibling and get its child.
> >
> >
> >
> > This is where I get struck. Each sibling can have children and they can
> > have
> > siblings. So how do I ensure I visit each node in the tree?
> >
> > Any tips or tricks for this would be grateful. As I could use this in
> other
> > situations.
> >
> >
> >
> > Sean
> >
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > To unsubscribe or change subscription options:
> > https://mail.python.org/mailman/listinfo/tutor
> >
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> https://mail.python.org/mailman/listinfo/tutor
>


-- 
Asad Hasan
+91 9582111698


More information about the Tutor mailing list