【问题标题】:OS X Terminal Output in PythonPython 中的 OS X 终端输出
【发布时间】:2013-09-19 19:21:41
【问题描述】:

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

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

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

以下是我的脚本,任何想了解我的新秀斗争的人:

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()

【问题讨论】:

    标签: python macos terminal


    【解决方案1】:

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

    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
    

    【讨论】:

    • 这可行,但偶尔会给我某些 .py 文件的“权限被拒绝”?编辑:谢谢下面的人,这是有道理的!
    • 你只能chmod你拥有的文件。如果您将其应用于其他帐户拥有的文件,则需要sudo chmod
    【解决方案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
    

    【讨论】:

    • 您似乎暗示必须设置x 才能运行python currenttime.py。事实并非如此。如果直接调用python,在currenttime.py上设置x没关系。
    • 我没有从我的回答中明白这一点,但我明白你为什么这么认为。
    猜你喜欢
    • 2010-10-29
    • 1970-01-01
    • 2016-11-04
    • 2011-11-13
    • 1970-01-01
    • 2011-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多