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

Question:

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

Asked By: Avinash Karhana

||

Answers:

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

Answered By: Povilas

OR to create a class:

gui.py:

from tkinter import *
from cli import C
def sb():
    c=en.get()
    zz=C(c).pr()
    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()

cli.py:

print("hello CLI run")
class C:
   def __init__(self,x):
      self.x=x
   def pr(self):
      return("this is what you typed = "+self.x)
Answered By: U12-Forward
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.