3

A program I wrote wasn't printing anything when I executed it out of the terminal, so I tried the ran the following code

import sys #!/usr/bin/python def main(argv): print "hell0\n" sys.stdout.flush() 

this is the terminal why is it not printing out hello. Is the main function even running?

0

6 Answers 6

8

Python does not automatically call main() (and you'll need to use the sys library to get argv).

#!/usr/bin/python import sys def main(): print "hell0\n" main() 
Sign up to request clarification or add additional context in comments.

Comments

3

You didn't call main anywhere, you've only defined it.

Comments

3

Two things: (1) your #!/use/bin/python needs to be the first thing in your file, and (2) you need to add a call to main. As it is, you're defining it, but not actually calling it.

In Python, you would not normally pass command-line arguments to main, since they are available in sys.argv. So you would define main as not taking any arguments, then call it at the bottom of your file with:

if __name__ == "__main__": sys.exit(main()) 

The test for __name__ prevents main from being called if the file is being imported, as opposed to being executed, which is the standard way to handle it.

If you want to explicitly pass the command line arguments to main, you can call it as:

if __name__ == "__main__": sys.exit(main(sys.argv)) 

which is what you would need to do with the definition you currently have.

2 Comments

@LimitedAtonement Oops, the way OP defined main you would need to pass arguments. I updated my answer.
Awesome! Five-year service honor!
1

In python your code doesn't have to be in a function, and all functions have to be explicitly called.

Try something like this instead:

#!/usr/bin/python import sys print "hell0\n" 

1 Comment

The shebang needs to be the very first line of the file.
-1

make sure you call the function after defining it,

defining a function only stores it in memory.

#!/usr/bin/python import sys def main(argv): print "hell0\n" sys.stdout.flush() main() 

1 Comment

It looks like his main function expects arguments, but you're not passing them?
-1

usually, people put some code at the end of the script to run the main(), e.g.

if __name__ == "__main__": main() 

Then, you can run your script in terminal, and it will call the main() method.

1 Comment

His main expects arguments, so you'll need to pass those, too, right?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.