Python does not allow additional comment with env python

徘徊边缘 提交于 2019-12-14 03:26:05

问题


I have a commenting line problem in python. I created a ages.py with vim and here is my script

#!/usr/bin/env python
ages={"dad":42, "mom":35, "lisa":7}
for item in ages:
        print item

When I add a comment above the !/usr/bin, like

# this is a python script
#!/usr/bin/env python
ages={"dad":42, "mom":35, "lisa":7}
for item in ages:
        print item

and after I go back to directory, which includes the same script, and run the script with writing to terminal ages.py but I get this error

$ ./ages.py
./ages.py: line 3: mom:35,: command not found
./ages.py: line 5: syntax error near unexpected token `print'
./ages.py: line 5: 'print item'

I know that when I remove the #!/usr/bin/env python line # works perfectly for commenting. However, I would like to add this line to run the script only writing its name to prompt. Otherwise, I have to write python ages.py every single time to run it, which I see as a burden.

1st Q: How can I comment to .py script with still having the '#!/usr/bin/env python' line

P.S: I've already tried """ ''' before and after comment line, it does not work either.

2nd Q: Is there a way to run a .py script in python environment? For instance, I can run .m file in octave simply writing its name to command line. But I could not figure out if there is a same way in python?

P.S: I know the questions are so easy and deserve -1, however, for new python users, the all answers will provide great information, thanks for all of them. It is so subtle solution but without it, I've constantly got the errors


回答1:


  1. the line containing #!/usr/bin/env python must be first, you can add your comments below;

  2. yes, you can do it like this: exec(open('yourscript.py').read()) - however, results might sometimes differ from your expectations.




回答2:


That first line is a very important one. It's called the Hashbang and sometimes known as the shebang. It tells the operating system what interpreter to use to execute the script. When the shebang is used, it has to be the first line. Other variations include

#!/bin/sh
#!/usr/bin/perl/
#!/usr/bin/python

These are for system default sh, perl and python. Any other comments in your code has to be after this line.



来源:https://stackoverflow.com/questions/44329841/python-does-not-allow-additional-comment-with-env-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!