Link to home
Start Free TrialLog in
Avatar of isuhendro
isuhendroFlag for Singapore

asked on

Include file / module / package in PYTHON

dear experts,
i have a working python script within one file, but would like to split some part of the code for easy maintenance
Below is partial of the script called it monitor.py, and I would like to remove class Activity defined within the script as something like "include" file, so that can be reused by other script.
Could you advice me?
Thanks!!
import re, os, time, thread
 
class Activity(object):
    def __init__(self, id=None, status=None, device_pin=None, start=None, duration=None, mobile=None, email=None):
        self.id = id
        self.status = status
        self.device_pin = device_pin
        self.start = start
        self.duration = duration
        self.mobile = mobile
        self.email = email
    def print_info(self):
        print self.id, ":" + self.device_pin + ","  + self.start +  ","  +self.duration +  ","  +self.mobile +  ","  +self.email
 
def process(activity):
    activity.print_info()
    print 'This is a thread for activity id %s' % (activity.id)
    
print "Starting"
opt_sleeping_time = 5
  
while True:
  print "Fetching new jobs"
  os.popen("copy jobs.xml jobs")

Open in new window

SOLUTION
Avatar of efn
efn

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Avatar of pepr
pepr

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of isuhendro

ASKER

hi efn, thanks for your explanation.. I did the same as you mentioned (saved class Activity as activity.py) and put the file inside the same directory of monitor.py (=c:\Documents and Settings\soehendr\My Documents\python\CA)  , and modify the necessary code.

1) add import activity
2) print sys.path (line 85 and 86) to confirm
But the application generate error below.

any ideas, which one is wrong?

Thanks.

sys.path =
c:\Documents and Settings\soehendr\My Documents\python\CA
C:\WINDOWS\system32\python25.zip
C:\Python25\DLLs
C:\Python25\lib
C:\Python25\lib\plat-win
C:\Python25\lib\lib-tk
C:\Python25
C:\Python25\lib\site-packages
Fetching new jobs
Traceback (most recent call last):
  File "monitor.py", line 194, in <module>
    _main(sys.argv)
  File "monitor.py", line 162, in _main
    activity = Activity()
NameError: global name 'Activity' is not defined


import re, os, time, thread, activity, sys, getopt
 
try:
  import syslog
except:  # for platforms without syslog that try to use --syslog option
  class fake_syslog:
    def openlog(self,foo):
      raise Exception("Syslog not supported on this platform")
    def syslog(self,foo):
      raise Exception("Syslog not supported on this platform")
  syslog = fake_syslog()
 
 
 
def Usage():
  print """
Usage python monitor.py
"""
 
def Options():
  print """
Usage  : python monitor.py [options]
Options:
  -p period   : sleeping periode inside monitoring loop
  -u URL      : central web URL
  -h            : print this help text 
"""
 
class Logger:
  #
  # open a new log file in the target dir if logging
  # a race condition if there are tons of scripts
  # starting at the same time and should really use locking
  # but that would be overkill for this app
  #
  def __init__(self, logname = "monitor.log", verbose = 0, logging = 0, use_syslog = 0):
    self.logname = logname
    self.verbose = verbose
    self.logging = logging
    self.syslog = use_syslog
    self.prefix = "monitor.py: "
 
    asctime = time.asctime(time.localtime(time.time()))
 
    if self.syslog:
      syslog.openlog("monitor")
    if self.logging:
      self.logfp = open(self.logname, "w")
      self.logfp.write(Useragent + "\n")
      self.logfp.write(self.prefix + asctime + "\n")
      self.logfp.write(self.prefix + "logging to " + self.logname + "\n")
      self.logfp.close()
    if self.verbose:
      print Useragent 
      print self.prefix + asctime 
 
  # normal logging message
  def logit(self, logline):
    if self.verbose:
      print self.prefix + logline
      if self.syslog:
        syslog.syslog(logline)
    if self.logging:
      self.logfp = open(self.logname, "a")
      self.logfp.write(self.prefix + logline + "\n")
      self.logfp.close()
 
  # logging message that gets printed even if not verbose
  def logexit(self, logline):
    print self.prefix + logline
    if self.logging:
      self.logfp = open(self.logname, "a")
      self.logfp.write(self.prefix + logline + "\n")
      self.logfp.close()
    if self.syslog:
      syslog.syslog(logline)
 
def process(activity):
    activity.print_info()
    print 'This is a thread for activity id %s' % (activity.id)
    
 
def _main(argv):
  #default options
  print "sys.path = " 
  for s in sys.path: print s
  opt_sleeping_time = 5
  opt_logging = 0
  opt_syslog  = 0
  opt_verbose = 0
  opt_period = 5
  opt_directory = "."
  opt_url = "http://localhost:3000"
  opt_new = "/activities/list?status=NEW"
 
  #if len(argv) == 1:
  #  Usage()
  #  sys.exit(0)
  
  try: #d:l:v:syslog:period:url:help
    loweropts = "d:l:v"
    upperopts = ""
    wordopts = ["syslog","period", "url", "help"]
    opts, args = getopt.getopt(argv[1:], loweropts+upperopts, wordopts)
  except getopt.error, reason:
    print reason
    sys.exit(-1)
 
  # check verbose, logging and detailed help options first
  # check directory to place logging file
  for opt in opts:
    (lopt, ropt) = opt
    if lopt == "-l":
      opt_logging = 1
    elif lopt == "-v":
      opt_verbose = 1
    elif lopt == "--syslog":
      opt_syslog = 1
    elif lopt == "--help":
      Usage()
      Options()
      sys.exit(0)
    elif lopt == "-d":
      if os.path.isdir(ropt):
        opt_directory = ropt
      else:
        print "Bad directory option, this directory " + ropt + "does not exist"
        sys.exit()
      # fix the dir name to end in slash
      if opt_directory[-1:] != "/" and os.name != "nt":
        opt_directory = opt_directory + "/"
      elif opt_directory[-1:] != "\\" :
        opt_directory = opt_directory + "\\"
 
  # create the logger object
  if opt_directory:
    logger = Logger(opt_directory + "jubilee.log", opt_verbose, opt_logging, opt_syslog)
    logline = "opt_directory set to " + opt_directory
    logger.logit(logline)
  else:
    logger = Logger("jubilee.log", opt_verbose, opt_logging, opt_syslog)
 
  # okay now parse rest of the options and log as needed
  #
  for opt in opts: #:period:url:
    (lopt, ropt) = opt
    opt_period = 5
    opt_url = "http://localhost:3000"
    if lopt == "--period":
      opt_period = ropt
      logline = "opt_period set to " + opt_period
      logger.logit(logline)
    elif lopt == "--url":
      opt_url = ropt
      logline = "opt_url set to " + opt_url
      logger.logit(logline)
      
  while True:
    print "Fetching new jobs"
    os.popen("copy jobs.xml jobs")
    f = open('jobs', 'r')
    activity = Activity()

Open in new window

Thank you so much!!
Avatar of efn
efn

Hi isuhendro,

I think the answer is in the comment above from my learned colleague pepr.  You posted your question after he posted his comment, but perhaps you hadn't seen it at that point.  Since you have now accepted it as the answer to your question, I trust it enabled you to solve your problem.  If not, post another question here and I'm sure someone will help you.

--efn
The Python style guide says to use

import x
import y
import z

instead of

import x, y, z

Now, the command

from activity import Activity


However, it is a good idea not to use the "activity" identifier in your script if you use the module with the same name.