Q:

How to check if code running is run directly via file or run via importing in some other file in python?

I am trying to make a CLI and GUI for a appliaction in which I am using my CLI to perform task and return string for my GUI and give output.
But problem is when I import my CLI it first takes input as it should when it is run from direct CLI, but I do not want it to take input from CLI when running from GUI.
So, for this is there any way from which I can check if the CLI script is run directly or from CLI or is imported in some file and then being run.
this is an example what I did:
cli.py
print("hello CLI run")
x=input()
def pr(x):
    return("this is what you typed = "+x)
print(pr(x))

gui.py
from tkinter import *
from cli import pr
def sb():
    c=en.get()
    zz=pr(c)
    expression.insert(0,zz)
win=Tk()
lbl=Label(win,text="Hello World")
lbl.pack()
en=Entry(win)
en.pack()
sn=Button(win,height = 2, width = 10,text="submit",command=sb)
sn.pack()
lbl=Label(win,text="Output :")
lbl.pack()
expression=Entry(win)
expression.pack()
win.mainloop()

When I run this this asks me to input in CLI first and then give CLI output and then run the GUI

A:

You should add your logic in to main function and then at the bottom of the file add
if __name__ == "__main__":
    # Do some validation
    main()

'main' is the name of the scope in which top-level code executes. A module’s __name__ is set equal to '__main__' when read from standard input, a script, or from an interactive prompt.

https://docs.python.org/3/library/main.html

