0

I see that %run filepath.py lets me execute the code in a .py file. However, it appears to only accept unquoted paths or paths quoted with ", not expressions that would evaluate to a path. For example these work:

%run ../some/dir/script.py

%run "../some/dir/script.py"

But these do not:

%run '../some/dir/script.py'
ERROR:root:File `"'../some/dir/script.py'.py"` not found.

%run "../some/dir/" + "script.py"
ERROR:root:File `'../some/dir/.py'` not found.

paths[1]
'../some/dir/script.py'
%run paths[1]
ERROR:root:File `'paths[1].py'` not found.

I am inferring that this is something to do with what a magic command is or does in IPython. However, I don't understand paths or order of evaluation in Python well enough to understand where in the documentation this behaviour would be described or figure out that this wouldn't work beforehand.

So the question: What is the best way to run many .py files from a Jupyter notebook, given that I know or can construct their paths with os.listdir or something else? Is there an alternative way to run a bunch of code? And what am I misunderstanding about how magic commands and paths work that led me to expect that I could do things like %run paths[1]?

All advice appreciated, new to Python ways.

EDIT: I am not trying to have personal methods or functions available in a notebook, which it seems like creating modules is for. These scripts are each creating particular large list objects (Earth Engine FeatureCollections) and are not really supposed to be reusable code, they are just big chunks of text. Example of first few lines of each one:

CLEAR_20160129T072832 = ee.FeatureCollection(
        [ee.Feature(
            ee.Geometry.Polygon(
                [[[43.29505920410156, 7.921873929606968],
                  [43.29814910888672, 7.8878678877391515],
                  [43.335227966308594, 7.883106818446446],
                  [43.341064453125, 7.9072516750710635],
                  [43.33179473876953, 7.925614422980302],
                  [43.297462463378906, 7.920853789152566]]]),
            {

ad nauseam for hundreds of lines.

Calum You
  • 14,687
  • 4
  • 23
  • 42
  • Possible duplicate of [How to include external Python code to use in other files?](https://stackoverflow.com/questions/714881/how-to-include-external-python-code-to-use-in-other-files) – Mariusz Mar 01 '18 at 22:16
  • I've just encountered the same issue re-running a code I wrote in another machine. Let me know if you've found a way around! – Nabla Sep 17 '18 at 20:33
  • What I ended up just doing was using string methods to get the commands as strings in a list, print that in a cell, and copy the output into a new cell... you can use alt-dragging and find/replace to remove the quotes. I can type that into an answer if it helps but it didn't really feel like a "solution" – Calum You Sep 19 '18 at 04:27

0 Answers0