Why won't my python code print anything?

前端 未结 6 942
梦如初夏
梦如初夏 2020-12-21 11:52

A program I wrote wasn\'t printing anything when I executed it out of the terminal, so I tried the ran the following code

import sys

#!/usr/bin/python

def          


        
相关标签:
6条回答
  • 2020-12-21 12:25

    usually, people put some code at the end of the script to run the main(), e.g.

    if __name__ == "__main__":
        main()
    

    Then, you can run your script in terminal, and it will call the main() method.

    0 讨论(0)
  • 2020-12-21 12:33

    Python does not automatically call main() (and you'll need to use the sys library to get argv).

    #!/usr/bin/python
    
    import sys
    
    def main():
        print  "hell0\n"
    
    main()
    
    0 讨论(0)
  • 2020-12-21 12:35

    You didn't call main anywhere, you've only defined it.

    0 讨论(0)
  • 2020-12-21 12:38

    make sure you call the function after defining it,

    defining a function only stores it in memory.

    #!/usr/bin/python
    
    import sys
    
    def main(argv):
        print  "hell0\n"
        sys.stdout.flush()
    
    main()
    
    0 讨论(0)
  • 2020-12-21 12:40

    Two things: (1) your #!/use/bin/python needs to be the first thing in your file, and (2) you need to add a call to main. As it is, you're defining it, but not actually calling it.

    In Python, you would not normally pass command-line arguments to main, since they are available in sys.argv. So you would define main as not taking any arguments, then call it at the bottom of your file with:

    if __name__ == "__main__":
        sys.exit(main())
    

    The test for __name__ prevents main from being called if the file is being imported, as opposed to being executed, which is the standard way to handle it.

    If you want to explicitly pass the command line arguments to main, you can call it as:

    if __name__ == "__main__":
        sys.exit(main(sys.argv))
    

    which is what you would need to do with the definition you currently have.

    0 讨论(0)
  • 2020-12-21 12:42

    In python your code doesn't have to be in a function, and all functions have to be explicitly called.

    Try something like this instead:

    #!/usr/bin/python
    
    import sys
    
    print  "hell0\n"
    
    0 讨论(0)
提交回复
热议问题