繁体   English   中英

导入python脚本作为模块时出现错误

[英]Getting error while importing a python script as module

我已经在Python代码下面编写了代码,并试图通过从python shell导入它作为模块来使用,但是它抛出错误。

def break_words(stuff):

"""This function will break up words fro us."""
    words = stuff.split('')
    return words

def sort_words(words):
"""sort the words."""
    return sorted(words)

def print_first_word(words):
 """Prints the first word after popping it off."""
    word=words.pop(0)
    print word

def print_last_word(words):
"""print the last word after poppomg it off."""
    word=words.pop(-1)
    print word

def sort_sentence(sentence):
    """Takes a full sentence and return the sorted word."""
    words= break_words(sentence)
    return sort_words(words)

def print_first_and_last(sentence):
    """Prints the first and last word of the sentences."""
    words = sort_sentence(sentence)
    print_first_word(words)
    print_last_word(words)

当我从python shell导入它时:-

>>> import Breaking_code

Traceback (most recent call last):
 File "<pyshell#4>", line 1, in <module>
    import Breaking_code
ImportError: No module named Breaking_code

我的目的是将其用作如下所示的模块

sentence = "All good things come to those who wait."
words = Breaking_code.break_words(sentence)
output:- ['All', 'good', 'things', 'come', 'to', 'those', 'who', 'wait.']

好的,您已经在要导入Shell的某个目录中编写了一个模块,但是模块的范围仅限于该模块所在的目录。

有两种选择

1,在系统环境变量中添加模块所在的目录,也可以通过代码来完成

import sys
sys.path.append("your\\ directory\\path here")
import breaking_code

2.只做快速目录更改

import os
os.chdir("your\\ directory\\path here") #changing current working directory
import breaking_code

Breaking_Code.py很可能不在Python Shell所在的文件夹中。如果尝试,则只需导入一个函数即可

从breaking_code导入sort_words

暂无
暂无

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

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