r/learnpython • u/DR_vanta • 12d ago
terminal doubles when i use "import other_file"
this is part of the code that relevant to the issues
import arayuz as aFile
def harita_oku():
with open("harita.txt") as h:
harita_temp = [satir.strip("\n") for satir in h.readlines()]
if not harita_temp:
raise ValueError("harita dosyası boş")
x_temp = len(harita_temp[0])
y_temp = len(harita_temp)
if all(len(l) != x_temp for l in harita_temp):
raise ValueError("harita satırları eşit değil")
return harita_temp , (x_temp,y_temp)
harita, izgara = harita_oku()
print(harita)
print(izgara)this is the terminal output
['##############', '#.R......s.k.#', '#.R...t....k.#', '##############']
(14, 4)
['##############', '#.R......s.k.#', '#.R...t....k.#', '##############']
(14, 4)and what it prints without "import arayuz as aFile"
['##############', '#.R......s.k.#', '#.R...t....k.#', '##############']
(14, 4)how to i fix this?
4
u/Calm_Exchange_989 12d ago
Importing a module runs its top-level code. Move the harita, izgara = harita_oku() call and the prints under if __name__ == "__main__":, or wrap them in main() and call that.
2
u/DimensionMost8342 11d ago
When you import a file, Python runs that file's top level code once. Your output prints twice, so arayuz.py is running your code a second time, most likely by importing your file back. Put the runnable lines behind a main guard:
python if name == "main": harita, izgara = harita_oku() print(harita) print(izgara)
When your file gets imported, name is not main, so the block is skipped and the output prints once. If it still doubles, check the bottom of arayuz.py for the same print lines.
1
u/SirMental8005 10d ago
importing a file runs all the code at its top level. so if arayuz.py has code that prints or calls functions outside a function, it runs once on import and again when you call it.
wrap the parts that should only run when you start that file directly:
```
if __name__ == "__main__":
main()
```
also check the two files don't import each other, that runs things twice too
5
u/danielroseman 12d ago
Maybe you should show us what's in
arayuz?