Solved

unable to compile using jython

Posted on 2010-09-17
7
601 Views
Last Modified: 2012-05-10
Hi,

I'm trying to compile a python program using jython and it's throwing below error

C:\jython2.2.1>jython test.py
Traceback (innermost last):
  (no code object) at line 0
  File "test.py", line 30
                    html = html if html else download(url, user_agent).read()
                                ^
SyntaxError: invalid syntax


Below is my python program. Please let me know how to resolve this.

0
Comment
Question by:sukumarr
  • 4
  • 3
7 Comments
 

Author Comment

by:sukumarr
ID: 33699767

import sys
import re
import urllib2
import urlparse
from optparse import OptionParser


# regular expression data for each website
VIDEO_DATA = [
    ('youtube.com', '%7C(.*?videoplayback.*?)%2C'),
    ('metacafe.com', '&mediaURL=(.*?)&'),
]
# default user agent to use when downloading
USER_AGENT = 'pytube'
# size of file to download
CHUNK_SIZE = 1024 * 1024



def scrape(url, html=None, user_agent=None, output=None):
    """Scrape video location from given url. 

    Use html instead of downloading if passed.
    Download file to output if passed.
    Return url of video if found, else None
    """
    netloc = urlparse.urlsplit(url).netloc
    for domain, video_re in VIDEO_DATA:
        if domain in netloc:
            html = html if html else download(url, user_agent).read()
            search = re.search(video_re, html)
            if search:
                flash_url = urllib2.unquote(search.group(1))
                if output:
                    print "Downloading flash to `%s'" % output,
                    #open(output, 'wb').write(download(flash_url, user_agent).read())
                    req = download(flash_url, user_agent)
                # testing with keyword in python
                    with open(output, 'wb') as fp:
                        chunk = True
                        while chunk:
                            chunk = req.read(CHUNK_SIZE)
                            if chunk:
                                fp.write(chunk)
                                #fp.flush()
                                print '.',
                                sys.stdout.flush()
                    print
                return flash_url
            else:
                raise PyTubeException('Failed to locate video regular expression in downloaded HTML')
    raise PyTubeException('URL did not match available domains')


def download(url, user_agent=None):
    """Download url and return data
    """
    headers = {'User-Agent' : user_agent}
    req = urllib2.Request(url, None, headers)
    return urllib2.urlopen(req)


class PyTubeException(Exception):
    pass



if __name__ == '__main__':
    # parse command line options
    parser = OptionParser(usage='usage: %prog, [-o <file.flv> -a <user_agent> -s -h] url')
    parser.add_option('-o', '--output', dest='output', help='Output file to download flash file to. If this is not specified file will not be downloaded.')
    parser.add_option('-s', '--sites', action='store_true', default=False, dest='sites', help='Display sites that pytube supports, then quit.')
    parser.add_option('-a', '--agent', dest='user_agent', default=USER_AGENT, help='Set user-agent for downloads.') 
    options, args = parser.parse_args()
    if options.sites:
        print '\n'.join(domain for (domain, reg) in VIDEO_DATA)
    else:
        if args:
            flash_url = scrape(args[0], user_agent=options.user_agent, output=options.output)
            if flash_url:
                print flash_url
        else:
            print 'Need to pass the url of the video you want to download'
            parser.print_help()

Open in new window

0
 
LVL 5

Expert Comment

by:-Richard-
ID: 33700567
I'm unaware of Python or Jython supporting an embeeded if statement such as that line contains.  I believe the intention of the code can be realized by the following:

if not html:
    html = download(url, user_agent).read()


   
0
 
LVL 5

Expert Comment

by:-Richard-
ID: 33700726
To elaborate somewhat, I recognize that the construct you attempted to use is similar to a Java construct which would compile just fine in Java.  You seem to be operating on the assumption that Jython is somehow "like" Java.  This is actually pretty much untrue.  Jython is an implementation of Python and syntactically is pure Python. However, Jython is implemented in Java, which allows it to integrate seamlessly with Java libraries and classes, to run under the Java virtual machine, and to be used in any Java environment.  But don't go trying to use Java syntax, it won't like it!
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:sukumarr
ID: 33700757
@Richard

I did as you said but it's throwing error as below



C:\jython2.2.1>jython test.py
Traceback (innermost last):
  (no code object) at line 0
  File "test.py", line 30
        if not html:
        ^
SyntaxError: invalid syntax
0
 
LVL 5

Accepted Solution

by:
-Richard- earned 500 total points
ID: 33701112
Interesting.  I tried your original program, including that embedded "if", under Python (not Jython) 2.6.4 and it had no syntax errors.  I tried it under Jython 2.5.1 and it got past that line with the "if", but gave me a syntax error saying "with will become a reserved keyword under Python 2.6".  That's a different issue, but it had no problem with that "if" construct, which surprised me.  Well, you learn something new every day.
 
What version of Jython are you using?  What is your operating system environment?  I'm in a Windows environment myself.

It is possible you are now having some kind of "weird" problem with the source file itself such as an unprintable character embedded in it somewhere that you don't see in your editor, or the file is sitting on top of a bad bit on your disk somewhere.  Deleting the file and creating a new one with the same contents might be beneficial.

Another suggestion I can make for finding an inexplicable problem like this is to follow the ever-tightening net principle.  Start eliminating code and see  if you still get the error.  At some point you can narrow it down to one thing you eliminate that fixes the problem, which may or may not be the actual line which the interpreter is complaining about.  When you find that one thing you will find the true problem.
0
 

Author Closing Comment

by:sukumarr
ID: 33701390
Perfect...and after copying my own code to notepad(Windows cista) and re-run again it worked. Also richard, i had a last question.

After running will Jython create some kind of class file like for ex: if we run test.py..will it generate test.class ?
0
 
LVL 5

Expert Comment

by:-Richard-
ID: 33701555
It is possible to make Jython do that, but it is not straigtforwards.  Here is a tutorial:  http://wiki.python.org/jython/JythonMonthly/Articles/September2006/1
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
linux date/time setting via python 6 68
Python On Mouseover Save URL/Link 4 77
python error - set 2 42
Help with a Python script converting xml to csv 4 47
Sequence is something that used to store data in it in very simple words. Let us just create a list first. To create a list first of all we need to give a name to our list which I have taken as “COURSE” followed by equals sign and finally enclosed …
Dictionaries contain key:value pairs. Which means a collection of tuples with an attribute name and an assigned value to it. The semicolon present in between each key and values and attribute with values are delimited with a comma.  In python we can…
Learn the basics of strings in Python: declaration, operations, indices, and slicing. Strings are declared with quotations; for example: s = "string": Strings are immutable.: Strings may be concatenated or multiplied using the addition and multiplic…
The goal of the tutorial is to teach the user how to how to load their YouTube profile onto Flash Media Live Encoder.

697 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question