5

I'm quite new to Python and programming in general.

I have created a few scripts using Python and as part of my framework/best practices for my scripts, I'd like to display when a script begins and ends in the IDLE shell. For now, I have just been adding a print function with the name of the script. So for example for a script called "UpdateMaps.py", I would have:

import arcpy, os

print "BEGIN: 'UpdateMaps'"  

<some script that updates maps>

print   "COMPLETED: 'UpdateMaps'"

But I would prefer to have the script name be printed automatically, since I often cut and paste pieces of script to another one, change the name of the scripts, etc.

So I would prefer something like this (I'm making up the 'str(scriptname)' object as an idea of what I'm looking for):

import arcpy, os

print "BEGIN: " + str(scriptname)  

<some script that updates maps>

print   "COMPLETED: " + str(scriptname)  

Is there a way to do that?

PolyGeo
  • 65,136
  • 29
  • 109
  • 338
Kari
  • 115
  • 1
  • 2
  • 6
  • This is a good question but it is about pure Python so would have been better researched/asked at [so]. – PolyGeo Jan 22 '16 at 19:41

1 Answers1

7

os.path.basename(__file__) is what I use (if your script name is your filename).

You might to consider using actual python logging as well. Your log statements can go to multiple targets (stdout, files, email, slack, tcp socket,etc). And you can get your expected output to console and then whatever else (usually file).

import logging
import os, sys

root = logging.getLogger()
root.setLevel(logging.DEBUG)

ch = logging.StreamHandler(sys.stdout)
ch.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
root.addHandler(ch)

root.info('BEGIN:  %s' % os.path.basename(__file__))

root.info('COMPLETED:  %s' % os.path.basename(__file__))

Output:

C:\Python27\ArcGIS10.3>python.exe C:\temp\test.py
2016-01-22 14:04:59,743 - root - INFO - BEGIN:  test.py
2016-01-22 14:04:59,743 - root - INFO - COMPLETED:  test.py

C:\Python27\ArcGIS10.3>
Jay Cummins
  • 14,642
  • 7
  • 66
  • 141
  • I figured it was something easy, this is exactly what I was looking for. Thanks Jay! – Kari Jan 22 '16 at 19:07