Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
There are no syntax error or compilation error found. Why is not this program executing? I am not able to catch why is this program not running if has no compilation errors. What could logically go wrong in this below code?
What can I add into this code to make it run and interact?
def main():
print "Checking platform...\r\r\r"
platform = systemdetails()
def systemdetails():
print "Hello! Welcome to the auto-commander"
print "Please enter the platform specific number to automate."
platforminput = integer(input ("1. Cisco 2. Linux/Unix 3. Juniper 4. VMware vSphere/NSX \n:"))
if platforminput ==1:
platform='cisco_ios'
elif platforminput ==2:
platform='linux'
elif platforminput ==3:
platform='juniper'
elif platforminput ==4:
platform='vmware'
else:
print "Commander has to repeat the question...\n\n"
systemdetails()
return platform
You'll need to call your main function. A minimal example that still reproduces your problem is
def main():
print "Hello World!"
To get this to work, you need to call your main
def main():
print "Hello World!"
main()
Generally you only want to call your main if you are not being imported, which can be done like so
def main():
print "Hello World!"
if __name__ == '__main__':
main()
You need to call your main() function.
Either like this:
main()
Or like this:
if __name__ == "__main__":
main()
In the second example, main() will only be called if you run the program directly rather than importing the module and running functions individually. This way, you can import the module's functions to use separately without main() running when importing.
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I have a simple Python code:
import sys
def main(argv1, argv2):
return 0
if __name__ == '__main__':
return main()
Basically I want the code to return to caller what main functions returns but I get the below error during execution:
$ python ../myexamples/sample.py
File "../myexamples/sample.py", line 11
return main()
^
SyntaxError: 'return' outside function
Is it that main method cannot return any value back to OS?
If the objective if to get the exit code back to the os at the end of the program execution it is possible using the exit function, the return statement can only be used inside function but a python program itself is not a function. So to answer your question you can do something like this
import sys
def main(argv1, argv2):
return 0
if __name__ == '__main__':
exit_code = main()
exit(exit_code)
"return" is only valid in function, so the valid code should be:
import sys
def main(argv1, argv2):
return 0
if __name__ == '__main__':
main()
And if you want get the return value of this function, the valid code should be:
import sys
def main(argv1, argv2):
return 0
if __name__ == '__main__':
return_value = main()
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I want a quick way to recognize a print line.
For example, in JS there is console.trace() that gives you an easy indication of where the print came from.
I know I can print a traceback but it is just too big for the task and makes following the code execution almost impossible.
I need something that wouldn't take a lot of room when printed and will point me to the correct line where that output was printed.
using the logging module you could try this:
import logging
logging.basicConfig(level=logging.DEBUG, format=("line %(lineno)d: %(message)s"))
def print_line(strg):
logging.debug(strg)
if __name__ == "__main__":
print_line("test")
which outputs
line 18: test
should this interfere with the rest of your logging you can also create and configure a dedicated logger (there may be better ways to do this)
import logging
import sys
print_line_logger = logging.getLogger("print_line")
print_line_logger.setLevel(logging.DEBUG)
formatter = logging.Formatter("line %(lineno)d: %(message)s")
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(formatter)
print_line_logger.addHandler(handler)
def print_line(strg):
print_line_logger.debug(strg)
Using the logging module as shown by #hiroprotagonist is probably the way to go, but because you mentioned you already have heavy use of logging, you could maybe want to use the inspect module.
This example will print the function where the print statement under DEBUG is executed; maybe this is sufficient for your needs?
DEBUG = True
if DEBUG:
import inspect
def _print(s):
print(f'now in: {inspect.stack()[1][3]} -> {s}')
def current_function():
if DEBUG:
_print('debug stuff')
print('doing stuff')
def main():
current_function()
if __name__ == '__main__':
main()
output:
now in: current_function -> debug stuff
doing stuff
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.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm having a problem where I want the user to be able to input text to call functions. It works perfectly fine except for one thing. :/ Once something has been input nothing can be done afterwards. The only way to solve it is run the program again which is not convenient. I have spent a lot of time looking for an answer and need help. I also think other amateurs like me might be wondering this too.
An example of the code:
x = raw_input('test1')
if x == 'x':
print 'test2'
The result:
test1x
test2
x
'x'
As you can see it works once then stops working. For the record I'm using Python 2. Hope this can be solved :)
You need to use a loop if you want to program to keep running.
Here is a simple example:
while True:
n = raw_input("Please enter 'hello':")
if n.strip() == 'hello':
break
The program will keep running until you type hello
You can use the following function
def call():
input = raw_input('input: ')
if input == 'yes':
print 'yes'
call()
call()
last_data = ''
while last_data != 'yes':
input = raw_input('ENTER SOMETHING: ')
#do whatever you want with input
last_data = raw_input('DO YOU WANT TO QUIT? (yes/no): ')
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
Here is my code
def main():
# This code reads in data.txt and loads it into an array
# Array will be used to add friends, remove and list
# when we quit, we'll overwrite original friends.txt with
# contents
print"Welcome to the program"
print "Enter the correct number"
print "Hockey fan 1, basketball fan 2, cricket fan 3"
choice = input("Select an option")
while choice!=3:
if choice==1:
addString = raw_input("Who is your favorite player??")
print "I love Kessel"
elif choice==2:
remInt = raw_input("Do you think that the Cavaliers will continue ther loosing ways?")
print "I think they can beat the Clippers"
else:
"You must choose a Number (1,2 or 3)"
print "Cricket is a great sport"
choice = input("Select an option")
inFile = open('data.txt','r')
listNumbers = []
for numbers in inFile:
listNumbers.append(numbers)
print numbers
inFile.close()
if __name__ == "__main__":
main() # will call the 'main' function only when you execute this from the command line.
Add:
if __name__ == "__main__":
main()
To your script (indented all the way to the left; not as part of the main() function).
Add:
if __name__ == "__main__":
main()
to the end of the file
You should try the following
if __name__ == "__main__":
main()
Once that is done, you should call your program as follows from the command line (assuming you are on Linux/Mac)
python <your_prog>
Also it will be helpful if you give the exact error that you are getting.
Also make sure that all the indentation is correct.