0

I two .py files:

file_1.py

file_2.py

file_1.py contains code that will open an raster and split it into sections. Similar to creating a grid and clipping to each grid within QGIS. I have a variable x set as my file that I want to use "raster.tif". I would like import this variable into file_2.py. I found this answer by @Ashwini Chaudhary (import file_1 then file_1.x). The problem I am facing is when I run file_2.py, file_1 is executing first. I simply want to access the variable and not execute the file. Is that possible to do?

Binx
  • 382
  • 7
  • 22
  • 1
    You can't. You can put the code you don't want to run in an `if __name__ == "__main__":` guard, though. That is the idiomatic way of making a module that you can import or execute directly without the importing running the code – juanpa.arrivillaga Feb 04 '21 at 18:31
  • IOW: "I simply want to access the variable and not execute the file. Is that possible to do?" no, that isn't possible. *How could it be*? – juanpa.arrivillaga Feb 04 '21 at 18:32
  • Sorry what does IOW mean? – Binx Feb 04 '21 at 18:34
  • 1
    "in other words" – juanpa.arrivillaga Feb 04 '21 at 18:34
  • Basically, the *variable doesn't exist* until the module is executed, and there is no way to partially execute a module to extract the value of a particular variable. An `import` *always* executes the entire module. It has to. I closed this as a duplicate, you should read through the accepted answer and structure your modules using the `if __name__ == "__main__"` idiom – juanpa.arrivillaga Feb 04 '21 at 18:36
  • Okay, yes I understand. Thank you! – Binx Feb 04 '21 at 20:53

1 Answers1

-2

This is not possible to do from the research i did. Sorry if i'm wrong

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343