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")?
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With