[bfprog] Packaging and Importing Custom Python Code

Forrest Thiessen thiessen at cyberscapearena.com
Wed Jun 22 08:01:10 PDT 2005


Ok, I've been messing around with this some, and here's where I'm at. .
. please bear in mind that this is a work-in-progress; I've done some
simple tests, and everything worked, but it's not ready for prime time yet!

(1) At the end of the file Battlefield 2 Server/python/bf/__init__.py
you add a single line: "import custom". That's the only change needed to
any of the EA/DICE Python files.
(2) In that same directory, you create a new directory, called "custom".
(3) In the new custom directory, you create a text file called
__init__.py, with the following contents:

--------------------------------------------------
  import os

  for item in os.listdir("custom"):
      if   item.endswith('.py'):  item = item[0:-3]
      elif item.endswith('.pyc'): item = item[0:-4]
   
      if item == '__init__': continue
   
      try:
          __import__('custom.'+item)
          print "custom." + item + ' imported.'
      except ImportError:
          print 'FAILED to import custom.' + item
--------------------------------------------------

(4) Profit!

At this point, any custom modules or packages can just be dropped into
the custom folder, and they will automatically be incorporated into BF2.

If you just want to register your own handlers, say, for a stats logging
system, this already does everything you need in a clean way.

What I haven't figured out yet: let's say you want to do something like
the changes to autobalancing that have been mentioned; that requires
replacing a method of an existing object from a different module.  I've
done this with Python before in slightly different circumstances, so I'm
sure it's possible; I just haven't figured out the correct syntax for it
yet.

--Forrest





More information about the BFProg mailing list