6

In python how can I create a function that can be global an used in all classes that are called? Here is an example:

import configparser
import os
import sys
from datetime import datetime
from ftplib import FTP

def notify(msg):
    echo = True
    log = True
    if echo:
        print(msg)
    if log:
        f = open('log.txt','a')
        msg = datetime.now().strftime("%y-%m-%d-%H:%M:%S")+': ' + msg
        f.write(msg)
        f.close()
    #sys.exit()  #removing this was the fix!

class zoneFTP():
    def __init__(self):
        self.conn = FTP()
        self.dir = './'
        notify('The dir is :' + self.dir)

def main():
    notify('starting')
    ftp = zoneFTP()

if __name__ == "__main__":
    main()

Calling notify() in the zoneFTP class fails. How can I make the notify() function like one of the python built in functions so that it can be called anywhere? Or is there a better way of doing what I am trying to accomplish here?

5
  • 1
    Check the error message you're getting. There should be no reason you can't call notify() from the class initializer, but the class name FTP is not declared. Commented Apr 23, 2011 at 1:04
  • 1
    Your notify calls sys.exit(), so the the call to zoneFTP() in main will never be reached. Commented Apr 23, 2011 at 1:13
  • @Steve Correct, The above code is picked from a larger project I am working on, I missed that part. I fixed the code example. Commented Apr 23, 2011 at 1:20
  • @Keith Thanks, I'm new to python and totally forgot I had that in there. It works just fine now! Commented Apr 23, 2011 at 1:21
  • 1
    haha, throwing sys.exit in random functions is generally a bad idea! Commented Apr 23, 2011 at 4:51

1 Answer 1

7

Put notify() in a utility module and have all the other modules import it.

Sign up to request clarification or add additional context in comments.

1 Comment

This is a good idea, and as I get more functions like this I may start using this method, removing sys.exit() fixed the problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.