This question already has answers here:
python: how to tell if file executed as import vs. main script?
(3 answers)
Closed 1 year ago.
Is possible to check within a function if the given function runs within the script or runs as an imported module in another script?
For example:
def func():
if func was imported:
do this
else: # it runs within the script
do that
Rewrite your function like this:
def func():
if __name__ == '__main__':
print("I'm running within this script.")
else:
print("I was imported to another script.")
if __name__ == '__main__':
func()
If you run the current script, you'll get the following output:
./test.py
>>> I'm running within this script.
If you run from test import func; func() you'll get the following:
>>> I was imported to another script.
Every module has a __name__, if it is imported it will be equal to the name of the module, else it will be '__main__' if it is in the script you run
def func():
if __name__ == '__main__':
# Do this
else:
# Do that
Related
import json
import django_facebook
def main():
token={"EAAYweZAE8V28BAEvrqNvhcwiC5Y2KahleAQihgEwKacedR82qEEYWZAGvgQc8OdinAyg6jSNEapN3GR4yBgXNQY9ta2bhuVsBclR8YKRKqDF5CdKmgW0NWRDZCKlvVkmE8ZB1NRqaN6uspKkR38ZA5eVLmROxSRZAm7xgPAfZC2jKSPVmGOYZCivg05pAj0w43CpAS4JKam8xwZDZD"}
graph=facebook.GraphAPI(token)
fields=['id,name,age_range,hometown']
profile=graph.get_object('me',fields=fields)
print(json.dumps(profile,indent=4))
if __name__=="main":
main()
i am creating this program and its executing but not showing output???
When a python module is executed as the principal entry point, the __name__ variable will be set to "__main__".
The line if __name__ == "__main__" therefore allows us to execute certain code if this module is being run explicitly and represents the main entry point to the program. Code inside that if block will not be executed if the module is imported from a different module.
In your case, you are testing __name__ against the string "main". You need to change this to "__main__" and your code will run as expected.
I have the file main.py containing the code
def my_function():
a = 0
b = 1
c = 2
if __name__ == "__main__":
my_function()
I execute this script from a terminal / shell.
If I run the script with python -i main.py all the variables are already gone because the function my_function has ran out of scope.
How do I interrupt the running of the script after the command a = 0 and set a to the value 1?
EDIT
My goal with this question is to learn how I can apply some commands on variables that are the result of a function, even after the function has finished. So the code I wrote above is just a (minimum working) example.
You can use Python debuger's set_trace() to break into the debugger from a running program and manipulate variables.
Use debugger command c(ont(inue)) to continue execution.
def my_function():
a = 0
import pdb
pdb.set_trace()
b = 1
c = 2
if __name__ == "__main__":
my_function()
I am doing a simple project on my Pycharm IDE.
My code is this:
import webbrowser
import time
socialMediaUrls = ["www.google.com","www.edureka.com"]
techUrls = ["www.udacity.com","www.dailymotion.com"]
def open_tabs(url_list):
for element in url_list:
webbrowser.open_new_tab(element)
def main():
webbrowser.open("www.youtube.com",new=0,autoraise=false)
time.sleep(1)
open.tab(socialMedialUrls)
open_tabs(techUrls)
main()
but after running I am getting this message:
C:\Users\adc\AppData\Local\Programs\Python\Python36-32\python.exe
C:/Users/adc/PycharmProjects/untitled1/ur.py
Process finished with exit code 0
And I am getting same message for all my projects. What should I do?
You should call main in that way:
def main():
webbrowser.open("www.youtube.com",new=0,autoraise=false)
time.sleep(1)
open.tab(socialMedialUrls)
open_tabs(techUrls)
if __name__ == "__main__":
main()
Also I see that your code contains some other errors. For example, in Python there is False keyword, not false. Lines with open.tab and open_tabs will not work too.
Currently, no instructions are reachable in your script (besides the import statements)
in:
def main():
webbrowser.open("www.youtube.com",new=0,autoraise=false)
time.sleep(1)
open.tab(socialMedialUrls)
open_tabs(techUrls)
main()
indentation suggests that you're performing a recursive call (which isn't what you want).
Unindent main() to make sure you execute something in your script.
Or put the instructions of main at zero-indent level outside any procedure (in that case, it is executed even when importing the module, probably not important here)
(note that python programs don't need a main(), this isn't C)
This question already has answers here:
Why doesn't the main() function run when I start a Python script? Where does the script start running (what is its entry point)?
(5 answers)
Closed 6 years ago.
I am writing a simple Python program with some functions, one of which is a main() function executes the other functions. However when I run the code below there is no output. Can someone tell me if they see an error in the structure?
def print1():
print("this is also a function")
def print2():
print("this is a function")
def main():
print1()
print2()
You need to call main(). Right now it is just a definition. What use is an entry in a dictionary if nobody uses the word?
def print1():
print("this is also a function")
def print2():
print("this is a function")
def main():
print1()
print2()
main()
It is common in Python programs to do things differently depending on if the file is being imported or run. When a file is executed, the __name__ variable is set either to '__main__' or the name of the file. It is set to '__main__' if the file is being executed as a python script, and it is set to the name of the file if it is being imported. You can use this information so that you don't actually run anything if it is just being imported instead of being run as a python script:
if __name__ == '__main__':
main()
That way, you can import the module, and use the functions without main() being called. If it is run as a python script, however, main() will be called.
Add this to the bottom of your code.
if __name__ == "__main__":
main()
See https://docs.python.org/2/library/main.html
Main needs to be called explicitly. You can do it without the if statement, but this allows your code to be either a module or a main program. If it is imported as a module, main() won't be called. If it is the main program then it will be called.
You are thinking like a C programmer. In this case python acts more like a shell script. Anything not in a function or class definition will be executed.
You need to call main() in order for it to run.
I believe what you mean to be doing is
def print1():
print("this is also a function")
def print2():
print("this is a function")
if __name__ == '__main__':
print1()
print2()
Call this script something.py and then run python something.py from your command line.
So in my file1.py, I have something like:
def run():
# Do something
print "Hi"
Now I want to use function run() in another file.
from file1.py import run
However, when I execute the other file it also prints Hi. How do I suppress this?
Add the print "Hi" in an if __name__ == "__main__" clause.
When python imports modules it executes the code contained in them in order to build the module namespace. If you run the module as the main script the __name__ is going to get assigned to __main__ and the code inside the if clause is going to get executed.
Since you're not running the script as the main script the __name__ gets assigned to the modules __name__ (in this case file1) and as a result this test will not succeed and the print statement is not going to get executed.
def run():
# Do something
if __name__ == "__main__":
print "Hi"
You should include after the functions this:
this runs the program
if main == "name":# before and after 'main' and 'name' there are two under_scores!
print "hi" etc...
if you don't want Hi to be printed, simply delete from your file1.py
if you want Hi to be printed when run() is called, then indent it so that it belongs to the run() function.