簡體   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