Why can't I print to terminal with my python script?
python, python-3.x, scripting, ubuntu
Solution
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")
Problem
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")?
Related problems
- Why doesn't print output show up immediately in the terminal when there is no newline at the end?
- Why doesn't the main() function run when I start a Python script? Where does the script start running (what is its entry point)?
- Why doesn't the main() function run when I start a Python script? Where does the script start running (what is its entry point)?