简体   繁体   English

运行“ ./script”会在导入语句后获得语法错误,但“ python脚本”可以正常工作

[英]running “./script” gets syntax error after import statements, but “python script” works fine

I'm doing something with the sys.argv in python here is the code: 我正在用python中的sys.argv做一些事情,这是代码:

age1.py age1.py

import datetime
import os
import sys

if len(sys.argv) == 2:
    now_time = datetime.datetime.now()
    future_time = now_time + datetime.timedelta(int(sys.argv[1]))
    print "date in", sys.argv[1],"days",future_time

elif len(sys.argv) == 4:
    print "three paras"
    spe_time = datetime.datetime(int(sys.argv[1]),int(sys.argv[2]),int(sys.argv[3]))
    now_time = datetime.datetime.now()
    diff_time = now_time - spe_time
    print "days since then..." , diff_time  

if I run the code in bash like: python age1.py xxxx, the program goes fine 如果我在bash中运行代码,例如:python age1.py xxxx,程序运行正常
but if I run that like ./age1.py xxxx, the mouse will become a symbol like "+", then the program ends up with: 但是,如果我像./age1.py xxxx这样运行,鼠标将变成像“ +”之类的符号,然后该程序最终显示为:

"./age1.py: line 5: syntax error near unexpected token `sys.argv'  
./age1.py: line 5: `if len(sys.argv) == 2:'

system: Ubuntu 10.10 系统:Ubuntu 10.10
Python 2.7.3 Python 2.7.3
any reason for that? 有什么原因吗?

You didn't add a #!/usr/bin/python to the start of your file. 您没有在文件开头添加#!/usr/bin/python

Your shell (bash) is trying to interpret the python file as if it were written in bash script, and failing. 您的shell(bash)试图将python文件解释为好像是用bash脚本编写的一样,但失败了。 Much like giving a French book to a 3-year-old English-speaking child, and the child thinking the words are English. 就像给三岁的说英语的孩子送一本法语书,并且那个孩子认为单词是英语一样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM