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.
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.
Why is it standard in Python to have the main() function and the if __name__ == '__main__' check at the end of the block of code? It also seems standard for the abstraction of the functions to follow the same pattern upwards. What I mean is that the definition of the function to be executed by main() is above the main() and the definition of the functions inside that are above and so on..
That seems odd because when one opens the module to read the code, it ends up starting with low-level code and moves up to higher level functions. Isn't it hard to grasp what the module is doing that way?
Why not do the alternative? Have the if __name__ check at the top followed by the main() function, and so on. This way, one quickly glances at what the main() function does and understands what the code is about.
You can't call main() before it is defined. And main cannot call other functions before they are defined.
Example 1:
if __name__=='__main__':
main()
def main():
print("Hello")
This will error because main hasn't been defined yet at the point where you try and execute it.
Example 2:
def main():
hello()
if __name__=='__main__':
main()
def hello():
print("Hello")
This will error because main() is executed and tries to call hello before it is defined.
The if __name__=='__main__': which contains the call to main() works best at the end of the file so that everything that it needs has been defined before it is reached.
Where you put the main definition itself is more flexible, but putting it at the end (just before the if __name__=='__main__': block that calls it) makes as much sense as anywhere else.
The purpose of an if __name__ == '__main__': guard is to prevent a module from having side-effects when it's imported.
The fact that it is a module rather than a script implies that it will normally be used by other code importing the definitions from it, not executed directly. So given that, it makes sense that the functions, classes and constants appear first in the source code, since those are what users of the module will be importing (and hence, what they might want to see the source of).
So even if the code guarded by if __name__ == '__main__': doesn't rely on the definitions in the module already having been evaluated (which would be unusual), this part of the code is usually the least important to the users of the module, so it doesn't belong at the start of the file.
I want to understand from which point a Python program starts running. I have previous experience in Java. In Java every program starts from main() function of it's Main class. Knowing this I can determine the execution sequence of other classes or functions of other Classes. I know that in Python I can control program execution sequence by using __name__ like this:
def main():
print("This is the main routine.")
if __name__ == "__main__":
main()
But when we don't use __name__ then what is the starting line of my Python program?
Interpreter starts to interpret file line by line from the beginning.
If it encounters function definition, it adds it into the globals
dict. If it encounters function call, it searches it in globals
dict and executes or fail.
# foo.py
def foo():
print "hello"
foo()
def test()
print "test"
print "global_string"
if __name__ == "__main__":
print "executed"
else:
print "imported"
Output
hello
global_string
executed
Interpreter starts to interpret foo.py line by line from the beginning like first the function definition it adds to globals dict and then it encounters the call to the function foo() and execute it so it prints hello.
After that, it adds test() to global dict but there's no function call to this function so it will not execute the function.
After that print statement will execute will print global_string.
After that, if condition will execute and in this case, it matched and will print executed.
I'm already struggeling some hours with a problem within my python project.
The situation is as follows:
I have a script A.py and a Script B.py
**Script A.py:**
#in this script the function def main() is running
def main():
#some coding in here
x=str(body)#then i assign the string of the variable body to a new variable x
#some other coding in here
if __name__=='__main__':
main()
REMIND: this a pseudo code to explain my struggle (the script as a standalone module is working properly) !
Now I have Script B.py (in the same folder)
**Script B.py** #in this script i try to run Script A.py and assign the value of variable x to a new variable in order to do furhter processing with it.
import A
A.main() # When importing the module and excuting its main() function by running B.py I see the values of variable x appearing on my screen
QUESTION: How can I assign the value of variable x now to a new variable so that i can do further processing with it in B.py ? Is this even possible ?
Cause after calling the main function of A.py no other operations are processed.
Please consider that I'm a relatively newby regaring programming over several modules.
I would be very glad for any help.
Thank you very much in advance
Kind regards
Slin
Ok i tried your approaches but still not getting the desired result.
A.py is a AMQP subscribing script (https://www.rabbitmq.com/tutorials/tutorial-one-python.html) (see below):
import pika
credentials = pika.PlainCredentials('admin', 'admin')
connection = pika.BlockingConnection(pika.ConnectionParameters('Ipaddress',
5672,
'/',
credentials))
#connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()
channel.exchange_declare(exchange='logs',
exchange_type='fanout')
result = channel.queue_declare(exclusive=True)
queue_name = result.method.queue
channel.queue_bind(exchange='logs',
queue=queue_name)
print(' [*] Waiting for logs. To exit press CTRL+C')
def callback(ch, method, properties, body):
x = str(body)
print str(x)
channel.basic_consume(callback,
queue=queue_name,
no_ack=True)
channel.start_consuming()
if __name__ == '__main__':
main()
B.py:
import pika
import A
A.main()
With the approaches so far i get the same as shown with the coding above.
I would like to assign x (which values can chane when A is running) to a new variable within B.py to do some processing to publish it afterwards with the counterpart script of A.py.
When executing B.py i receive:
[*] Waiting for logs. To exit press CTRL+C
['20'] #this is the string of variable x from script A
Now i want to assign this ['20'] to a new variable wihtin B.py.. but the script B.py keeps running A.main() (which is logical cause it is a loop).
Thanks so far for your support.
Kind regards
You could return the value of x to script B using the return statement:
return str(body)#then i assign the string of the variable body to a new variable x
Then get this value in script B by storing it in a variable x = A.main().
Make x as a global variable inside A.py
**Script A.py:**
#in this script the function def main() is running
x = ''
def main():
global x
#some coding in here
x=str(body)
#then i assign the string of the variable body to a new variable x
if __name__=='__main__':
main()
Now you can access that x from B.py as A.x
Just treat it like you do with any other module. In script A, create a function as you have called main. In it you have to have a variable that you can insert from the other script, call it body.
Script A:
def main(body):
...
return x
Next you import the other script like you would any other model, using import _.py as _. The you use the function as you would in the other script, B. It is as if you are importing an object A and calling its method b.
Script B:
import a.py as A
object = A.main(thing2string) # or object = A.main() if the script b has something to return
Now you have the object that is created in A from that you can process in be. For example,
processed = [object[i] for i in object]
# ... processing steps
I don't know if you can have it notify you on change. But you use a timer to check if the value is updated and use an if statement to update if it has.
Summary:
You have to add the return line in script A. And you have to set a variable equal to it in script b. This new variable then becomes whatever b returns.
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.