7

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")?

2
  • 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. Commented Oct 27, 2016 at 23:52
  • "How do I print to the terminal if not with sys.stdout.write("string")? " Did you try using... print? Commented Jan 3, 2023 at 0:40

1 Answer 1

21

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")
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.