web-dev-qa-db-fra.com

Importer Python Script dans un autre?

Je passe par Learn Python The Hard Way et je suis sur la leçon 26.) de Zed Shaw. Dans cette leçon, nous devons corriger du code, qui appelle les fonctions à partir d'un autre script. nous n'avons pas besoin de les importer pour réussir le test, mais je suis curieux de savoir comment nous le ferions.

Lien vers la leçon | Lien vers le code à corriger

Et voici les lignes de code particulières qui font appel à un script précédent:

words = ex25.break_words(sentence)
sorted_words = ex25.sort_words(words)

print_first_Word(words)
print_last_Word(words)
print_first_Word(sorted_words)
print_last_Word(sorted_words)
sorted_words = ex25.sort_sentence(sentence)
print sorted_words
print_first_and_last(sentence)
print_first_a_last_sorted(sentence)
51
astroblack

Cela dépend de la structure du code du premier fichier.

Si c'est juste un tas de fonctions, comme:

# first.py

def foo(): print("foo")
def bar(): print("bar")

Ensuite, vous pouvez l'importer et utiliser les fonctions comme suit:

# second.py
import first

first.foo()    # prints "foo"
first.bar()    # prints "bar"

ou

# second.py
from first import foo, bar

foo()          # prints "foo"
bar()          # prints "bar"

ou, pour importer tous les symboles définis dans first.py:

# second.py
from first import *

foo()          # prints "foo"
bar()          # prints "bar"

Remarque: Cela suppose que les deux fichiers se trouvent dans le même répertoire.

Cela devient un peu plus compliqué lorsque vous souhaitez importer des symboles (fonctions, classes, etc.) dans d'autres répertoires ou dans des modules.

88
jedwards

Il est important de noter que (au moins dans python 3), pour que cela fonctionne, vous devez disposer d'un fichier nommé __init__.py dans le même répertoire.

21
soungalo

La suite a fonctionné pour moi et cela semble très simple aussi:

Supposons que nous souhaitons importer un script ./data/get_my_file.py et accéder à la fonction get_set1 ().

import sys
sys.path.insert(0, './data/')
import get_my_file as db

print (db.get_set1())
2
devil in the detail

J'espère que ce travail

def break_words(stuff):
    """This function will break up words for us."""
    words = stuff.split(' ')
    return words

def sort_words(words):
    """Sorts 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):
    """Prints the last Word after popping it off."""
    Word = words.pop(-1)
    print(Word)

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

def print_first_and_last(sentence):
    """Prints the first and last words of the sentence."""
    words = break_words(sentence)
    print_first_Word(words)
    print_last_Word(words)

def print_first_and_last_sorted(sentence):
    """Sorts the words then prints the first and last one."""
    words = sort_sentence(sentence)
    print_first_Word(words)
    print_last_Word(words)


print ("Let's practice everything.")
print ('You\'d need to know \'bout escapes with \\ that do \n newlines and \t tabs.')

poem = """
\tThe lovely world
with logic so firmly planted
cannot discern \n the needs of love
nor comprehend passion from intuition
and requires an explantion
\n\t\twhere there is none.
"""


print ("--------------")
print (poem)
print ("--------------")

five = 10 - 2 + 3 - 5
print ("This should be five: %s" % five)

def secret_formula(start_point):
    jelly_beans = start_point * 500
    jars = jelly_beans / 1000
    crates = jars / 100
    return jelly_beans, jars, crates


start_point = 10000
jelly_beans, jars, crates = secret_formula(start_point)

print ("With a starting point of: %d" % start_point)
print ("We'd have %d jeans, %d jars, and %d crates." % (jelly_beans, jars, crates))

start_point = start_point / 10

print ("We can also do that this way:")
print ("We'd have %d beans, %d jars, and %d crabapples." % secret_formula(start_point))


sentence = "All god\tthings come to those who weight."

words =  break_words(sentence)
sorted_words =  sort_words(words)

print_first_Word(words)
print_last_Word(words)
print_first_Word(sorted_words)
print_last_Word(sorted_words)
sorted_words =  sort_sentence(sentence)
print (sorted_words)

print_first_and_last(sentence)
print_first_and_last_sorted(sentence)
0
Amar