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()
Related
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
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I wrote the parser log_file. But i can`t understand why I can not call a function in this block.
Help me please.
Python is dependant on indentation. In order for the program to work you need to add the correct indentation to your code. That involves 4 spaces for each loop or flow control.
Here are a few that do:
def
if
while
for
Your problem is that Python does not know where to end the while loop without indentation.
Here is an example:
for in range(5):
print('Working')
if i == 4:
print('yes')
else:
print('no')
There are two ways to indent this.
How does Python know whether the if statement should be in the for loop or not? Both the following are valid with very different results:
for in range(5):
print('Working')
if i == 4:
print('yes')
else:
print('no')
OR
for in range(5):
print('Working')
if i == 4:
print('yes')
else:
print('no')
In the first the while prints out the message 5 times and then the if statement starts.
In the second the if is part of the while loop so it runs 5 times as well as printing the message.
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 5 years ago.
Improve this question
I'm having trouble with this code. It will run normally until it gets to the loop (def Game) and just stops there. I did have it as an if statement but that still didn't work. Please note that this may be a bit messy.
import random
import time
GameInProgress = ("Yes")
TutorialDone = ("No")
ReplayGame = ("Yes")
#Test purposes
PlayerName = ("Lewis")
print ("Welcome to 'Guess The Word!")
def Game():
GameInProgress = ("Yes")
TutorialDone = ("No")
ReplayGame = ("Yes")
#Test purposes
PlayerName = ("Lewis")
print ("Welcome to 'Guess The Word!")
WordSelected=("No")
LettersGuessed=0
print (TutorialDone)
EnterName = input("Would you like to enter your name?").title()
def Game(): is not a loop, it is a function it does not execute until you call it.
you can call a python function in this way
Game()
if you want to call the same function again and again simply you can call the function inside a for or while loop:
while(condition):
Game()
if your are very beginner follow some tutorials
https://www.tutorialspoint.com/python/python_functions.htm
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.
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.