Python中的OS X终端输出

时间:2013-09-19 19:21:41

标签: python macos terminal

这对于某人来说是最容易解决的问题,但我似乎无法找到答案。我有一个非常简单的程序,可以打印日期和时间。我正试图从OS X中的终端运行它,因为当我把它交给我的教授时它会如何运行。我被告知运行此方法的方法是使用如下命令:

XXX-MacBook-Air:~ XXX$ sudo chmod a+x /Users/[path]/currenttime.py

但是当我这样做时,脚本中的print语句不会输出任何地方。我不确定它是应该在终端输出,还是打印到哪里。

以下是我的剧本,适合那些想要了解我新手挣扎的更多信息的人:

import datetime

#!/usr/bin/env python

def currenttime():
date1 = str(datetime.datetime.now())
day = date1[8:10] #not stripped at all
day2= day.lstrip("0") #strip leading zeros
if len(day2) == 2:
    #then we have a two digit day and we should work with the last digit
    if day2[1] == 1:
        day_suffix = 'st'
    elif day2[1] == 2:
        day_suffix = 'nd'
    elif day2[1] == 3:
        day_suffix = 'rd'
    else:
        day_suffix = 'th'
else:
    #one digit day, run off the single digit
    if day2 == 1:
        day_suffix = 'st'
    elif day2 == 2:
        day_suffix = 'nd'
    elif day2 == 3:
        day_suffix = 'rd'
    else:
        day_suffix = 'th'
month = date1[5:7]
#we can use the month to search through a dictionary and return the english name
month_dict= {'01' : 'January', '02': 'February', '03': 'March', '04': 'April', '05': 'May', '06': 'June', '07': 'July', '08': 'August', '09': 'September', '10': 'October', '11': 'November', '12': 'December'}
year = date1[0:4]
hour = date1[11:13]
minute = date1[14:16]
print("Printed on the " + day2 + day_suffix + " day of " + month_dict[month] + ", " + year + " at " + hour + ":" + minute)

currenttime()

2 个答案:

答案 0 :(得分:4)

这不是运行它的方式。这是一种简单的方法:

XXX-MacBook-Air:~ XXX$ python /Users/[path]/currenttime.py

另外,您可以通过做两件事来安排避免上一行中的python

1)将您的脚本与python关联。将此行设置为脚本的第一行:#!/usr/bin/env python

2)通过运行以下命令将此程序标记为可执行文件:

XXX-MacBook-Air:~ XXX$ chmod a+x /Users/[path]/currenttime.py

然后,每次要运行程序时都要执行以下操作:

XXX-MacBook-Air:~ XXX$ /Users/[path]/currenttime.py

答案 1 :(得分:2)

sudo chmod a+x /Users/[path]/currenttime.py设置Python脚本的执行权限,以便可以执行。它实际上并没有执行它。

要执行脚本,请显式调用 python 解释器:

python /Users/[path]/currenttime.py

或者您可以/可能应该将#!/usr/bin/env python移动到您文件的第一行。然后你可以直接执行你的python脚本。

/Users/[path]/currenttime.py
相关问题