6

I can't figure out why I can't print to the terminal using the following code.

#!/usr/bin/env python3
import sys
def main():
    sys.stdout.write("Hello")

I'm running the program from the terminal by moving into the directory in which the python file is found, making the file executable and running

./filename

The terminal prints nothing, just goes to newline. How do I print to the terminal if not with sys.stdout.write("string")?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
dimly_lit_code
  • 113
  • 1
  • 2
  • 8
  • 1
    I haven't done *that* much in Python, but don't you need to call `main()` after you define it? Or just `print("Hello")` directly, without restricting it to the `main()` function. – Wildcard Oct 27 '16 at 23:52
  • "How do I print to the terminal if not with sys.stdout.write("string")? " Did you try using... `print`? – Karl Knechtel Jan 03 '23 at 00:40

1 Answers1

19

Python doesn't execute main (or any other) function by default.
You can either just do:

#!/usr/bin/env python3
import sys
sys.stdout.write("Hello")

or if you want to keep the function, but call it when the script is run:

#!/usr/bin/env python3
import sys

def main():
    sys.stdout.write("Hello")

if __name__ == '__main__':
    main()

The second method should be used if you are going to import the script into some other file, but otherwise, use the first one.

Also, you can just use the Python print function, which writes to stdout by default.

#!/usr/bin/env python3
print("Hello")
wjandrea
  • 28,235
  • 9
  • 60
  • 81
Munir
  • 3,442
  • 3
  • 19
  • 29