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?

dcousina
  • 157
  • 1
  • 1
  • 7

6 Answers6

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()
personjerry
  • 1,045
  • 8
  • 28
3

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

wim
  • 338,267
  • 99
  • 616
  • 750
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.

Tom Karzes
  • 22,815
  • 2
  • 22
  • 41
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"
Zain Rizvi
  • 23,586
  • 22
  • 91
  • 133
  • The [shebang](https://en.wikipedia.org/wiki/Shebang_(Unix)) needs to be the very first line of the file. – tripleee Dec 11 '17 at 09:33
-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()
Alvaro Bataller
  • 487
  • 8
  • 29
-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.