9

I've been writing Python in my text editor so I have a Python script, script.py. I'm still developing it so don't want to put it in my toolbox yet, and at the moment this means copying and pasting it from my text editor to the Python window in ArcGIS Desktop.

Is there a command that lets me call it from the ArcGIS Python window?

Something along the lines of:

run script.py

It seems logical that it should exist, but perhaps not.

1
  • You are constructing your script in a text editor? Get yourself the free pyscripter ide, it will be the best thing you'll ever do!
    – Hornbydd
    Commented Oct 7, 2013 at 9:28

2 Answers 2

17

You could use execfile.

For instance,

>>> execfile(r'c:\my\script.py')
4

I am not sure of your level of experience, but before you get too far in you will want to learn some best practices in Python. It would be more idiomatic, or "Pythonic", to modularize your code into functions/classes, import your module, and call one or more functions/classes.

If you want to make changes and interactively test the already-imported module, you can use the reload built-in function.

Use the if __name__ == '__main__' trick to protect your script's main procedure (everything other than imports, function/class declarations, and maybe some module-level variable declarations) from automatically running upon importing the module, and only execute that logic when running the script directly, e.g. from a command prompt or through ArcToolbox.

Then you can test specific parts of your module by just calling the relevant classes/functions.

2
  • 1
    Then you have to deal with the reload() function and all the nastiness of module caching and such in Python. If you're iteratively writing some small script in a text editor, this is a bit overkill. Commented Oct 4, 2013 at 23:53
  • 1
    I haven't had any problems with reload as long as I avoid using from module import x or from module import *.
    – blah238
    Commented Oct 5, 2013 at 1:02

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.