【问题标题】:Learn Python The Hard Way ex 25艰难地学习 Python 前 25
【发布时间】:2015-12-14 03:20:17
【问题描述】:

我在《Learn Python The Hard Way》一书中做练习 25。不幸的是,我遇到了一个问题:我无法在作为练习的一部分的 python shell 中导入 ex25 脚本。事实上,我尝试导入其他练习(包括来自 Project Euler 的一些练习和我制作的计算器 :)),我注意到即使我更改了脚本的名称,导入也不起作用,并且唯一有效的是一个称为“格式化程序”。

这是 ex25 的代码:

def break_words (stuff):
    #This function will separate words with spaces
    words = stuff.split(" ")
    return words

def sort_words(words):
    # This function sorts the words 
    return sorted(words)

def print_first_words(words):
    # Prints the first letter of a word by popping it
    word = words.pop(0)
    return word

def print_last_word(words):
    # This function prints the last letter of a word by popping it
    word = words.pop(-1)
    print word

def sort_sentence (sentence):
    # Takes in a full sentence and returns the sorted sentence
    words = break_words(sentence)
    return sort_words

def print_first_and_last(sentence):
    # Prints the first and last words of a sentence
    words = break_words (sentence)
    print_first_word(words)
    print_last_word(words)

def print_first_and_last_sorted(sentence):
    # Sorts the words the prints the first and last one
    words = sort_sentence(sentence)
    print_first_word(words)
    print_last_word(words)

这是“格式化程序”代码:

while True:
    for i in ["/","-","|","\\","|"]:
        print "%s\r" % i,

而且我还注意到,在书中,当作者运行脚本时,他会像“python scriptName.py”那样执行,而我只需要像“python scriptName”那样执行即可

【问题讨论】:

  • 您在尝试导入时遇到什么错误?
  • 您是否收到错误消息?或者你能解释一下当你尝试导入时会发生什么?
  • 如果你的脚本叫做 scriptName 而不是 scriptName.py ,那么你不能导入它。但是你仍然可以通过python scriptName在shell中运行它...
  • @KevinGuan 你的意思是“不能导入它”对吗?
  • @aneroid:糟糕,错字。固定。

标签: python import


【解决方案1】:

来自the document

模块是包含 Python 定义和语句的文件。文件名是后缀.py的模块名。在模块中,模块的名称(作为字符串)可用作全局变量 __name__ 的值。

正如我在 cmets 中所说的:

如果您的脚本名为 scriptName 而不是 scriptName.py,则无法导入它。但是您仍然可以通过python scriptName 在shell 中运行它。

然后重命名并添加后缀.py 即可。

【讨论】:

  • 我的脚本被称为“脚本”并且有一个 .py 扩展名(保存为 python 文件)它仍然可以工作吗?
  • @Supermexicano2002:那么它应该可以正常工作,您导入脚本时遇到什么错误?
  • 它告诉我没有名为 ex25 的模块
  • @Supermexicano2002:所以你的脚本叫做ex25.py,当你尝试import ex25时,它说没有这样的模块,对吧?
  • 没关系,当我保存文件时,我没有将其命名为“ex25.py”,而是将其命名为“ex25”并将其保存为 python 文件。所以我只需要重命名脚本“ex25.py”就可以了,但是谢谢!
猜你喜欢
  • 2013-04-06
  • 1970-01-01
  • 1970-01-01
  • 2016-05-14
  • 1970-01-01
  • 2011-12-04
  • 2016-06-28
  • 1970-01-01
相关资源
最近更新 更多