Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I print to terminal with my python script?

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

like image 756
dimly_lit_code Avatar asked Oct 27 '16 23:10

dimly_lit_code


1 Answers

Firstly, please ask programming questions on Stackoverflow unless they are specific to Unix/Linux shell programming.

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")
like image 121
Munir Avatar answered Oct 26 '22 07:10

Munir