Brandyn
Brandyn

Reputation: 1017

Linking Python Files Assistance

I understand how to actually link python files, however, i don't understand how to get variable's from these linked files. I've tried to grab them and I keep getting NameError.

How do I go about doing this? The reason i want to link files is to simply neaten up my script and not make it 10000000000 lines long. Also, in the imported python script, do i have to import everything again? Another question, do i use the self function when using another scripts functions?

ie;

Main Script:

import sys, os
import importedpyfile

Imported Py File

import sys, os

Upvotes: 2

Views: 290

Answers (3)

Michael Rawson
Michael Rawson

Reputation: 1975

I understand how to actually link python files, however, i don't understand how to get variable's from these linked files. I've tried to grab them and I keep getting NameError.

How are you doing that? Post more code. For instance, the following works:

file1.py

#!/usr/bin/env python

from file2 import file2_func, file2_variable

file2_func()
print file2_variable

file2.py:

#!/usr/bin/env python

file2_variable = "I'm a variable!"

def file2_func():
    print "Hello World!"

Also, in the imported python script, do i have to import everything again?

Nope, modules should be imported when the python interpreter reads that file.

Another question, do i use the self function when using another scripts functions?

Nope, that's usually to access class members. See python self explained.

There is also more than one way to import files. See the other answer for some explanations.

Upvotes: 3

selbie
selbie

Reputation: 104569

I think what you are trying to ask is how to get access to global vars from on .py file without having to deal with namespaces.

In your main script, replace the call to import importedpyfile to say this instead

from importedpyfile import *

Ideally, you keep the code the way you have it. But instead, just reference those global vars with the importedpyfile namespace.

e.g.

import importedpyfile
importedpyfile.MyFunction()  # calls "MyFunction" that is defined in importedpyfile.py

Upvotes: 2

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799150

Python modules are not "linked" in the sense of C/C++ linking libraries into an executable. A Python import operation creates a name that refers to the imported module; without this name there is no (direct) way to access another module.

Upvotes: 1

Related Questions