No access file en python si pas exécuté en "run in terminal"

Bonjour,

Je suis développeur sur python en environnement Debian et je rencontre un petit problème avec un de mes scripts. Je ne peux pas ouvrir un fichier que ce soit en lecture ou écriture si j’exécute directement le script dans le terminal via la commande : $ ./monScript.py.
L’erreur rencontrée est :

[quote]Traceback (most recent call last):
File “serverReport.py”, line 68, in
f= open(’./reportsFiles/report_’ + dateReport, ‘w’)
IOError: [Errno 2] No such file or directory: ‘./reportsFiles/report_2010-02-09’[/quote]

Par contre si je je double clic sur mon script et que je clique sur “run in terminal” le script s’exécute correctement.

Pour information : Mon script est bien en mode exécutable et les répertoires que j’utilise sont tous en droit 777. Vous trouverez ci dessous l’intégralité de mon script. Je suis connecté en root.

J’utilise une Debian Lenny. Uname -a me retourne : Linux vm-lenny-test 2.6.26-1-486 #1 Sat Jan 10 17:46:23 UTC 2009 i686 GNU/Linux

Deux questions : Pourquoi cela fonctionne en mode “run in terminal” et pas quand je fais un run du script directement dans le terminal ? Y’a t’il une possibilité de forcer le mode “run in terminal” pour ne pas rencontrer ce problème ?

Merci d’avance pour votre aide sur ce sujet.
Nabil

Intégralité de mon script python :


#!/usr/bin/python

# pre-requisites (debian)
# apt-get install python-mysqldb
# apt-get install python-amara

import MySQLdb
import datetime

lastTime=24 #last time in hour we want get notifications
errList = list() #Contains list of new ERR notifications
rmdrList = list() #Contains list of RMDR notifications

conn = MySQLdb.connect (host = "localhost",
                        user = "root",
                        passwd = "xxxx",
                        db = "xxxx")
cursor = conn.cursor ()

#Get the ERR and RMDR occured since the last time
#between(0,12)=ERR, between(16,17)=RMDR 
#See enum NotificationConstants.NotificationCause for the completed list
cursor.execute (
"""SELECT message 
      FROM notification 
      WHERE created > DATE_ADD(now(), INTERVAL -%s HOUR) 
      AND cause BETWEEN 0 AND 12
      ORDER BY severity""",(lastTime))

while (1):
    row = cursor.fetchone ()
    if row == None:
        break
    print("message : %s" % row[0])
    
    errList.append(row[0]) #add the new err to the list
    
print "Number of err returned: %d" % cursor.rowcount

cursor.execute (
"""SELECT message 
      FROM notification 
      WHERE created > DATE_ADD(now(), INTERVAL -%s HOUR) 
      AND cause BETWEEN 16 AND 17
      ORDER BY severity""",(lastTime))

while (1):
    row = cursor.fetchone ()
    if row == None:
        break
    print("message : %s" % row[0])
    
    rmdrList.append(row[0]) #add the new err to the list
    
print "Number of rmdr returned: %d" % cursor.rowcount

cursor.close ()
conn.close ()

#the name of the file report is equal of the current date
dateReport = str(datetime.datetime.date(datetime.datetime.utcnow()))

#Create file if not exist
try :
    f= open('./reportsFiles/report_' + dateReport, 'r')
    f.close()
except IOError:
    f= open('./reportsFiles/report_' + dateReport, 'w')
    f.close()


#open file in append mode
isErr = False
isRmdr = False
textMail='' #represents the body text of the mail

f= open('./reportsFiles/report_' + dateReport, 'a')
f.write('>>>>NOTIFICATIONS ERR<<<<\n')
textMail = textMail+'>>>>NOTIFICATIONS ERR<<<<\n' 

for item in errList:    
    f.write(str(item)+'\n')
    textMail = textMail+str(item)+'\n' 
    isErr = True

f.write('>>>>NOTIFICATIONS RMDR<<<<\n')
textMail = textMail+'>>>>NOTIFICATIONS RMDR<<<<\n'
for item in rmdrList:
    f.write(str(item)+'\n')
    textMail = textMail+str(item)+'\n' 
    isRmdr = True
f.close()


############################################################################
#EMAIL PROCESSING
############################################################################
from email.mime.multipart import MIMEMultipart
from smtplib import SMTPHeloError, SMTPException, SMTPSenderRefused, SMTPDataError
import mimetypes
from email.mime.base import MIMEBase
from email import encoders
import datetime
import socket

#define parameters of email
outer = MIMEMultipart()
outer['From'] = 'staging-alerts@xxxx.net'
outer['To'] = 'nsellami@xxxx.net'
if isErr:
    outer['Subject'] = socket.gethostname() +' >> '+errList.__getitem__(0)
else:
    outer['Subject'] = socket.gethostname()

#define smtp parameters
import smtplib
server = smtplib.SMTP('auth.smtp.1and1.fr', 587)
server.login('testsystem@xxxx.net', 'xxxxxx');

#attach the text of the mail
from email.MIMEText import MIMEText
textMsg = MIMEText(textMail)
outer.attach(textMsg)

#add the attachement (file report of the current day)
filename='report_'+str(datetime.datetime.date(datetime.datetime.utcnow()))
path='./reportsFiles/'+filename
#ctype, encoding = mimetypes.guess_type(path)
#if ctype is None or encoding is not None:
    # No guess could be made, or the file is encoded (compressed), so
    # use a generic bag-of-bits type.
ctype = 'application/octet-stream'
maintype, subtype = ctype.split('/', 1)
fp = open(path, 'rb')
msg = MIMEBase(maintype, subtype)
msg.set_payload(fp.read())
fp.close()
# Encode the payload using Base64
encoders.encode_base64(msg)
# Set the filename parameter
msg.add_header('Content-Disposition', 'attachment', filename=filename)
outer.attach(msg)


#send the email
try :
    composed = outer.as_string()
    failed = server.sendmail(outer['From'], outer['To'],composed)
except SMTPHeloError :
    print('SMTPHeloError')
except SMTPException :
    print('SMTPException')
except SMTPSenderRefused :
    print('SMTPSenderRefused')
except SMTPDataError :
    print('SMTPDataError')
    
server.quit()