3
votes

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?

6

6 Answers

7
votes

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()
3
votes

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
votes

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

1
votes

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
votes

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
votes

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.