Python Programming
 
Forums: » Register « |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support | 
User Name:
Password:
Remember me

The Shed is going Social! Join us on FaceBook and Twitter and chime in on the conversation.

Go Back   Dev Shed ForumsProgramming LanguagesPython Programming

Reply
Add This Thread To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 
Thread Tools Search this Thread Rate Thread Display Modes
 
Unread Dev Shed Forums Sponsor:
  #1  
Old February 27th, 2004, 04:45 PM
rickt's Avatar
rickt rickt is offline
Registered User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Feb 2004
Posts: 23 rickt User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: < 1 sec
Reputation Power: 0
Question Variables in and out of a function?

I have a problem with my function (this is my first attempt at making a function). Before I created the function my app ran just fine. Relevant code portion follows:

Code:
file('NIDS.html','w').write((post("MH")))
print 'Grabbed the NIDS.HTML and wrote the file.'
if os.path.isfile('NIDS_Original.html'):
    match = filecmp.cmp('NIDS.html', 'NIDS_Original.html')
    if match == False:
        shutil.copyfile('NIDS.html', 'c:\\documents and settings\\all users\\desktop\\ALERT Symantec Page Changed.html')
        shutil.copyfile('NIDS.html', 'NIDS_Original.html')
        print 'FALSE:  Copied NIDS.html to ALERT on the desktop.'
    else:
	    print 'TRUE:  Deleted the temp file NIDS.html.'
	    os.remove('NIDS.html')
else:
    print 'NIDS_Original.html not found.  Please Re-run the application again.'
    print 'A new NIDS_Original.html has been created.'
    shutil.copyfile ('NIDS.html', 'NIDS_Original.html')


This works fine. If the files NIDS_Original.html doesn't exist the program simply goes from if os.path.isfile to the last else statement and copies the NIDS.html (which is created by the first function not shown above for sake of brevity) to the file NIDS_Original.html.

Now I've created a function to peform the above piece of code and it fails with this error:
Traceback (most recent call last):
File "C:/temp/SymantecGet2.py", line 39, in -toplevel-
results_compare(fname)
File "C:/temp/SymantecGet2.py", line 22, in results_compare
match = filecmp.cmp(fname, fname+'_Original.html')
File "C:\Python23\lib\filecmp.py", line 49, in cmp
s2 = _sig(os.stat(f2))
OSError: [Errno 2] No such file or directory: 'NIDS.html_Original.html'


Here's the offending piece of code (I'll post more if needed, I just wasn't sure if that would be ok to do since it's kinda big):

Code:
def results_compare (fname):
    """Compare Results of files made from HTTP connect."""
    if os.path.isfile(fname):
#        print fname
        match = filecmp.cmp(fname, fname+'_Original.html')
        if match == False:
            shutil.copyfile(fname, 'c:\\documents and settings\\all users\\desktop\\ALERT - Symantec '+fname+' Page Changed.html')
            shutil.copyfile(fname, fname+'_Original.html')
            print 'FALSE:  Copied '+fname+' to ALERT on Desktop.'
        else:
                print 'TRUE: Deleted the temp file '+fname+'.'
                os.remove(fname)
    else:
        print fname+'_Original.html not found.  Please Re-run the application again.'
        print 'A new '+fname+'_Original.html has been created.'
        shutil.copyfile (fname, fname+'_Original.html')
#BODY of code
fname = "NIDS.html"
file(fname, 'w').write((post("MH")))
print 'Grabbed the '+fname+' and wrote the file.'
results_compare(fname)


post is another function I created which works fine with "MH" being passed the way it is. That's why I'm not clear on why the new function I made doesn't work.

Also, I think that using fname in the main body of the program and in a function is bad or wrong but I'm not sure. Guidance would be appreciated.

And for those of you who watched American Idol this season or who've seen his video circulated the "W": I've had no formal programming training what-so-ever.

Reply With Quote
  #2  
Old February 27th, 2004, 05:54 PM
percivall percivall is offline
Contributing User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Jul 2003
Posts: 133 percivall User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: < 1 sec
Reputation Power: 10
NIDS_Original.html and NIDS.html_Original.html are not the same files. That seems to be a problem. Try using `os.path.splitext()` to get a tuple with the name and the extension (including dot).

Reply With Quote
  #3  
Old February 27th, 2004, 07:59 PM
netytan's Avatar
netytan netytan is offline
Hello World :)
Dev Shed Frequenter (2500 - 2999 posts)
 
Join Date: Mar 2003
Location: Hull, UK
Posts: 2,537 netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level)netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level)netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level)netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level)netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level)netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level)netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level) 
Time spent in forums: 1 Week 2 Days 18 h 17 m 47 sec
Reputation Power: 68
Send a message via ICQ to netytan Send a message via AIM to netytan Send a message via MSN to netytan Send a message via Yahoo to netytan
You also have a very wierd indentation level in there but as perc said, the error you have is all about the filename. Anyway i've done a little house cleaning on your function and am up with this.

Code:
#!/usr/bin/env python

import filecmp, os, shutil

def compare(filename = 'NIDS.html', original = 'NIDS_Original.html'):
    
    if os.path.isfile(original):

        match = filecmp.cmp(filename, original)

        if match:
            os.remove(filename)
            print 'TRUE: Deleted the temp file ' + filename + '.'
        else:
            shutil.copyfile(filename, 'C:/Documents and Aettings/All Users/Desktop/ALERT - Page Changed.html')
            shutil.copyfile(filename, original)
            print 'FALSE: Copied ' + filename + ' to ALERT on Desktop.'


Tidy as it is i havn't had the opertunity to test it so chances are there'll be a few bugs. Also the function currently does nothing if an original file doesn't exist (os.path.isfile)... in reality we should probably call the function which first creates the original file but i'll leave that bit up to you

Mark.
__________________
programming language development: www.netytan.com Hula


Last edited by netytan : February 27th, 2004 at 08:02 PM.

Reply With Quote
  #4  
Old February 27th, 2004, 08:22 PM
rickt's Avatar
rickt rickt is offline
Registered User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Feb 2004
Posts: 23 rickt User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: < 1 sec
Reputation Power: 0
Post

I'm not sure why my indentation is wierd. <shrug> I'm just using what the TkPythonShell gives me. Except that I delete 4 spaces when I go from IF to ELSE. If you can, let me know how I'm messing up the indentations.

I still don't think my problem is solved. So, to avoid confusion here's my two pieces of cold. Sorry this is getting long!

Working without problem:
Code:
import urllib, httplib, filecmp, os, shutil
#POST FUNCTION v is for value ;)
def post(v):
    """Send the POST data v to the web server."""
    params = urllib.urlencode({'R':'yes','D':v})
    h = httplib.HTTP('securityresponse.symantec.com:80')
    h.putrequest('POST', '/avcenter/cgi-bin/updates_msa.cgi')
    h.putheader('Content-length', '%d' % len(params))
    h.putheader('Accept', 'text/plain')
    h.putheader('Host', 'securityresponse.symantec.com')
    h.endheaders()
    h.send(params)
    reply, msg, hdrs = h.getreply()
    print reply
    data = h.getfile().read()
    return data
#NIDS SECTION
file('NIDS.html','w').write((post("MH")))
print 'Grabbed the NIDS.HTML and wrote the file.'
if os.path.isfile('NIDS_Original.html'):
    match = filecmp.cmp('NIDS.html', 'NIDS_Original.html')
    if match == False:
        shutil.copyfile('NIDS.html', 'c:\\documents and settings\\all users\\desktop\\ALERT Symantec Page Changed.html')
        shutil.copyfile('NIDS.html', 'NIDS_Original.html')
        print 'FALSE:  Copied NIDS.html to ALERT on the desktop.'
    else:
	    print 'TRUE:  Deleted the temp file NIDS.html.'
	    os.remove('NIDS.html')
else:
    print 'NIDS_Original.html not found.  Please Re-run the application again.'
    print 'A new NIDS_Original.html has been created.'
    shutil.copyfile ('NIDS.html', 'NIDS_Original.html')
#HIDS SECTION
file('HIDS.html','w').write((post("HS")))
print 'Grabbed the HIDS.HTML and wrote the file.'
if os.path.isfile('HIDS_Original.html'):
    match = filecmp.cmp('HIDS.html', 'HIDS_Original.html')
    if match == False:  
        shutil.copyfile('HIDS.html', 'c:\\documents and settings\\all users\\desktop\\ALERT Symantec HIDS Page Changed.html')
        shutil.copyfile('HIDS.html', 'HIDS_Original.html')
        print 'FALSE:  Copied HIDS.html to ALERT on the desktop.'
    else:
	    print 'TRUE:  Deleted the temp file HIDS.html.'
	    os.remove('HIDS.html')
else:
    print 'HIDS_Original.html not found.  Please Re-run the application again.'
    print 'A new HIDS_Original.html has been created.'
    shutil.copyfile ('HIDS.html', 'HIDS_Original.html')
#SESA SECTION
sesa = httplib.HTTP('www.symantec.com:80')
sesa.putrequest('GET', '/techsupp/enterprise/products/sesa/sesa_1.1/files.html')
sesa.putheader('Accept', 'text/plain')
sesa.putheader('Host', 'www.symantec.com')
sesa.endheaders()
reply, msg, hdrs = sesa.getreply()
print reply
data = sesa.getfile().read()
file('SESA.html','w').write(data)
if os.path.isfile('SESA_Original.html'):
    match = filecmp.cmp('SESA.html', 'SESA_Original.html')
    if match == False:
        shutil.copyfile('SESA.html', 'c:\\documents and settings\\all users\\desktop\\ALERT Symantec SESA Page Changed.html')
        shutil.copyfile('SESA.html', 'SESA_Original.html')
        print 'FALSE:  Copied SESA.html to ALERT on the desktop.'
    else:
            print 'TRUE:  No updates for SESA.  Deleted the temp file SESA.html.'
            os.remove('SESA.html')
else:
    print 'SESA_Original.html not found.  Please Re-run the application again.'
    print 'A new SESA_Original.html has been created.'
    shutil.copyfile ('SESA.html', 'SESA_Original.html')
#http://www.symantec.com/techsupp/en...ym_2/files.html
#IFORCE SECTION
iforce = httplib.HTTP('www.symantec.com:80')
iforce.putrequest('GET', '/techsupp/enterprise/products/sesa/sesa_1.1/files.html')
iforce.putheader('Accept', 'text/plain')
iforce.putheader('Host', 'www.symantec.com')
iforce.endheaders()
reply, msg, hdrs = iforce.getreply()
print reply
data = iforce.getfile().read()
file('iForce.html','w').write(data)
if os.path.isfile('iForce_Original.html'):
    match = filecmp.cmp('iForce.html', 'iForce_Original.html')
    if match == False:
        shutil.copyfile('iForce.html', 'c:\\documents and settings\\all users\\desktop\\ALERT Symantec iForce Page Changed.html')
        shutil.copyfile('iForce.html', 'iForce_Original.html')
        print 'FALSE:  Copied iForce.html to ALERT on the desktop.'
    else:
            print 'TRUE:  No updates for iForce.  Deleted the temp file iForce.html.'
            os.remove('iForce.html')
else:
    print 'iForce_Original.html not found.  Please Re-run the application again.'
    print 'A new iForce_Original.html has been created.'
    shutil.copyfile ('iForce.html', 'iForce_Original.html')
    os.remove('iForce.html')


That code works, and if the files don't exist they are created and the user gets a prompt to run the app again.

Here's the revision I've done adding a second function (and now the app doesn't run and I get the error listed in my previous post):

Code:
import urllib, httplib, filecmp, os, shutil
#POST FUNCTION v is for value ;)
def post(v):
    """Send the POST data v to the web server."""
    params = urllib.urlencode({'R':'yes','D':v})
    h = httplib.HTTP('securityresponse.symantec.com:80')
    h.putrequest('POST', '/avcenter/cgi-bin/updates_msa.cgi')
    h.putheader('Content-length', '%d' % len(params))
    h.putheader('Accept', 'text/plain')
    h.putheader('Host', 'securityresponse.symantec.com')
    h.endheaders()
    h.send(params)
    reply, msg, hdrs = h.getreply()
    print reply
    data = h.getfile().read()
    return data
#POST RESULTS FUNCTION fname is for filename ;)
def results_compare (fname):
    """Compare Results of files made from HTTP connect."""
    if os.path.isfile(fname):
#        print fname
        match = filecmp.cmp(fname, fname+'_Original.html')
        if match == False:
            shutil.copyfile(fname, 'c:\\documents and settings\\all users\\desktop\\ALERT - Symantec '+fname+' Page Changed.html')
            shutil.copyfile(fname, fname+'_Original.html')
            print 'FALSE:  Copied '+fname+' to ALERT on Desktop.'
        else:
                print 'TRUE: Deleted the temp file '+fname+'.'
                os.remove(fname)
    else:
        print fname+'_Original.html not found.  Please Re-run the application again.'
        print 'A new '+fname+'_Original.html has been created.'
        shutil.copyfile (fname, fname+'_Original.html')
#BODY of code
# NIDS
fname = "NIDS.html"
file(fname, 'w').write((post("MH")))
print 'Grabbed the '+fname+' and wrote the file.'
results_compare(fname)
#HIDS
fname = "HIDS.html"
file(fname, 'w').write((post("HS")))
print 'Grabbed the '+fname+' and wrote the file.'
results_compare(fname)
#SESA SECTION
sesa = httplib.HTTP('www.symantec.com:80')
sesa.putrequest('GET', '/techsupp/enterprise/products/sesa/sesa_1.1/files.html')
sesa.putheader('Accept', 'text/plain')
sesa.putheader('Host', 'www.symantec.com')
sesa.endheaders()
reply, msg, hdrs = sesa.getreply()
print reply
data = sesa.getfile().read()
file('SESA.html','w').write(data)
if os.path.isfile('SESA_Original.html'):
    match = filecmp.cmp('SESA.html', 'SESA_Original.html')
    if match == False:
        shutil.copyfile('SESA.html', 'c:\\documents and settings\\all users\\desktop\\ALERT Symantec SESA Page Changed.html')
        shutil.copyfile('SESA.html', 'SESA_Original.html')
        print 'FALSE:  Copied SESA.html to ALERT on the desktop.'
    else:
            print 'TRUE:  No updates for SESA.  Deleted the temp file SESA.html.'
            os.remove('SESA.html')
else:
    print 'SESA_Original.html not found.  Please Re-run the application again.'
    print 'A new SESA_Original.html has been created.'
    shutil.copyfile ('SESA.html', 'SESA_Original.html')
#http://www.symantec.com/techsupp/en...ym_2/files.html
#IFORCE SECTION
iforce = httplib.HTTP('www.symantec.com:80')
iforce.putrequest('GET', '/techsupp/enterprise/products/sesa/sesa_1.1/files.html')
iforce.putheader('Accept', 'text/plain')
iforce.putheader('Host', 'www.symantec.com')
iforce.endheaders()
reply, msg, hdrs = iforce.getreply()
print reply
data = iforce.getfile().read()
file('iForce.html','w').write(data)
if os.path.isfile('iForce_Original.html'):
    match = filecmp.cmp('iForce.html', 'iForce_Original.html')
    if match == False:
        shutil.copyfile('iForce.html', 'c:\\documents and settings\\all users\\desktop\\ALERT Symantec iForce Page Changed.html')
        shutil.copyfile('iForce.html', 'iForce_Original.html')
        print 'FALSE:  Copied iForce.html to ALERT on the desktop.'
    else:
            print 'TRUE:  No updates for iForce.  Deleted the temp file iForce.html.'
            os.remove('iForce.html')
else:
    print 'iForce_Original.html not found.  Please Re-run the application again.'
    print 'A new iForce_Original.html has been created.'
    shutil.copyfile ('iForce.html', 'iForce_Original.html')
    os.remove('iForce.html')

# THINGS TO ADD
# 1.  If can't reach internet print out message indicated such.
# 2.  If can't reach individual pages indicate such.
# 3.  Open a new window and keep it open if user chooses.  -w as a flag?
# 4.  Add normal stuff like usage information
# 5.  Loop nids and hids section
# 6.  Set up framework for e-mail notification of page changes
# 7.  Download new files if available


So far what I've learned is that I can and should leave spaces in between filenames (or variables?) and single quoted information that are joined by a "+". And I need to figure out why my indentations are wrong.

Thanks for all the help so far!

Last edited by netytan : February 28th, 2004 at 06:33 AM.

Reply With Quote
  #5  
Old February 28th, 2004, 03:08 AM
percivall percivall is offline
Contributing User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Jul 2003
Posts: 133 percivall User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: < 1 sec
Reputation Power: 10
You're right. It doesn't work. That's because you haven't fixed what I told you to fix.

What I said in my original post was that "NIDS_Original.html" is not the same as "NIDS.html_Original.html". If you write fname + "_Original.html" you'll get "NIDS.html_Original.html"; but you compare that name to "NIDS_Original.html".

Look at my original post to see how you should fix your problem.

Last edited by percivall : February 28th, 2004 at 03:13 AM.

Reply With Quote
  #6  
Old February 28th, 2004, 06:55 AM
netytan's Avatar
netytan netytan is offline
Hello World :)
Dev Shed Frequenter (2500 - 2999 posts)
 
Join Date: Mar 2003
Location: Hull, UK
Posts: 2,537 netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level)netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level)netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level)netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level)netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level)netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level)netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level) 
Time spent in forums: 1 Week 2 Days 18 h 17 m 47 sec
Reputation Power: 68
Send a message via ICQ to netytan Send a message via AIM to netytan Send a message via MSN to netytan Send a message via Yahoo to netytan
I've highlighted the badly indented parts of you're first code. The stange thing is they all appear to be in the same place after an else statment.

Whenever you start a new block in Python, code inside that block should be indented durrr . But it's also important:

1. not to mix tabs and spaces
2. take care to indent blocks by the same amount (four spaces is the standard).

If IDLE is giving you problems i'd look at nother editor personally i havn't used IDLE in months...

http://www.python.org/cgi-bin/moinmoin/PythonEditors

There are a few ways you can strip the extension from the end of you're file name. it's really up to you which you use. As demonstrated in my function i like to provide both the required file names although assuming you dont want to do that...

Code:
name = os.path.splitext(name)[0]
name + '_Original.html'
...
name = name.replace('.html', '_Original.html') # requires a .html extention
...
name = name[-5:] + '_Original.html'


Note: all of these should work with you're current filenames but if the name changes (particually the extention) then you'll need to edit these examples a bit.

Mark.

Last edited by netytan : February 28th, 2004 at 07:01 AM.

Reply With Quote
  #7  
Old February 28th, 2004, 12:07 PM
rickt's Avatar
rickt rickt is offline
Registered User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Feb 2004
Posts: 23 rickt User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: < 1 sec
Reputation Power: 0
Unhappy

Again, thanks for the sugestions netytan and percivall. I fixed the tab problem I created. I think I just kept copy+paste the same section over and over so I only made the mistake once but then I perpetuated it.

OMG! I'm an idiot. I just wrote this huge post trying to explain things and I figured it out! percivall pointed it right out but I missed it. How obtuse I am!

In my original code I wrote:
Code:
if os.path.isfile(NIDS_Original.html):

I fubar'd the code because I was looking to see if NIDS.html exists. Of course it does! I just created it! What I need to change is from fname to:
Code:
if os.path.isfile(fname +'_Original.html'):

And check if NIDS.html_Original.html exists.

Thanks guys.

I'm going to clean up the code a bit more and see if I can figure out tuples and os.path.splitext.

Sorry if this looks lame to you guys. I'm kinda excited because this is my first program.

I started checking out the other editors also. I've installed the wxPython package but I'm having trouble figuring that stuff out. In the default python shell (IDLE) you can open a new window and type in the app there then hit F5 to run it. But I can't find the same capability in the pyCrust or pyShell. PyAlaCart appears to be the same thing as opening a new window from IDLE without the benefit of having the F5 function key to run the app through the IDLE. Did I miss something basic here? I'll have to double check through the forums because I remember reading about that same question in another thread.

Again, thanks!
-Rick

Reply With Quote
  #8  
Old February 29th, 2004, 03:40 PM
Grim Archon's Avatar
Grim Archon Grim Archon is offline
Mini me.
Dev Shed Novice (500 - 999 posts)
 
Join Date: Nov 2003
Location: Cambridge, UK
Posts: 783 Grim Archon User rank is Corporal (100 - 500 Reputation Level)Grim Archon User rank is Corporal (100 - 500 Reputation Level)Grim Archon User rank is Corporal (100 - 500 Reputation Level)Grim Archon User rank is Corporal (100 - 500 Reputation Level)  Folding Points: 1488 Folding Title: Novice Folder
Time spent in forums: 3 Days 2 h 15 m 57 sec
Reputation Power: 12
Send a message via MSN to Grim Archon
Editors

You shouldn't be worrying about IDLE, it's perfect for Python. I've written some quite large projects with it as the only editor. It has some useful features that you won't get as standard in more general code editors.

The biggest issue is mixing tabs and spaces, you can get in a real pickle pasting in source code that has used the tab character instead of spaces. IDLE automatically uses spaces even when you press the Tab key so if you write all your code with IDLE then you should not have a problem

Don't worry about removing the extra empty line, it's irritating but does not affect the logic.
Grim
__________________
*** Experimental Python Markup CGI V2 ***

Reply With Quote
Reply

Viewing: Dev Shed ForumsProgramming LanguagesPython Programming > Variables in and out of a function?

Developer Shed Advertisers and Affiliates



Thread Tools  Search this Thread 
Search this Thread:

Advanced Search
Display Modes  Rate This Thread 
Rate This Thread:


Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
View Your Warnings | New Posts | Latest News | Latest Threads | Shoutbox
Forum Jump

Forums: » Register « |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support | 
  
 


Powered by: vBulletin Version 3.0.5
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.

© 2003-2013 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap