Nur einzelne von Modul a nach modul b importieren

Wenn du dir nicht sicher bist, in welchem der anderen Foren du die Frage stellen sollst, dann bist du hier im Forum für allgemeine Fragen sicher richtig.
Antworten
rusb
User
Beiträge: 9
Registriert: Donnerstag 20. Oktober 2016, 10:53

Hallo Leute,
Wie schaffe ich das dass man von einem Modul nur eine bestimmte Variable in einem anderen Modul importiert

Code: Alles auswählen

# liveplot.py
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib import style

style.use('fivethirtyeight')

fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)

global xs             

def animate(i):
    lines = open('live.txt','r').read().split('\n')
    xs = []
    ys = []

    for line in lines:
        if len(line) > 1:
            x, y = line.split(',')
            xs.append(x)
            ys.append(y)
    ax1.clear()
    ax1.plot(xs, ys)

ani = animation.FuncAnimation(fig, animate, interval = 1000)
plt.show()

Code: Alles auswählen

from liveplot import xs 
print(liveplot.xs)
irgendwie importiert er beim zweiten modul wirklich alles vom ersten modul. und führt sogar modul "liveplot" komplett aus. Ich will aber nur dass
die variable xs importiert wird vom modul "liveplot".....
Zuletzt geändert von Anonymous am Dienstag 15. November 2016, 20:59, insgesamt 1-mal geändert.
Grund: Quelltext in Python-Codebox-Tags gesetzt.
Sirius3
User
Beiträge: 17741
Registriert: Sonntag 21. Oktober 2012, 17:20

@rusb: alles was nicht in Funktionen steckt, wird beim Importieren ausgeführt. Daher steht auch in Modulen immer fast alles in Funktionen. Ein »global« auf oberster Ebene hat übrigens keinen Effekt, weil das ja schon der globale Scope ist. Und sonst hat »global« meist nur negative Effekte. Es gibt sogar einen ImportError, weil die Variable xs nirgends definiert wird. Wenn Du also nicht willst, dass etwas ausgeführt wird, pack es in eine Funktion.
Antworten