75

I'm writing a Python program for fun but got stuck trying to import a function from a class in another file. Here is my code:

#jurassic park mainframe

from random import randint
from sys import exit
from comm_system import Comm_system #the file i want to import from



class Jpark_mainframe(object):
    def mainframe_home(self):
        print "=====Welcome to the Jurassic Park Mainframe====="
        print "==========Security Administration==============="
        print "===========Communications Systems==============="
        print "===============System Settings=================="
        print "===================Quit========================="

        prompt = raw_input("What would you like to do? ")

        while prompt != "Quit":

            if prompt == "Security Administration":
                print "Please enter the 5-digit passcode:"
                security_passcode = "%d%d%d%d%d" % (2, 0, 1, 2, randint(1, 2))
                security_guess = raw_input(": ")
                security_guesses = 0

                while security_guess != security_passcode and security_guesses < 7:
                    print "Incorrect. Please enter the security passcode."
                    security_guesses += 1
                    security_guess = raw_input(": ")

                    if security_guess == security_passcode:
                        print "=========Security Administration======="
                        print "Area 1 Fences: Off"
                        print "Area 2 Fences: On"
                        print "Area 3 Fences: Off"
                        print "Velociraptor Compound: Off"
                        print "Lobby Security System: Off"
                        print "Entrance Facility System: Off"
                        print "To enable all systems, enter 'On'"


                        enable_security = raw_input(": ")

                        if enable_security == "On":
                            print "Systems Online."


            if prompt == "System Settings":
                print "You do not have access to system settings."
                exit(0)


            if prompt == "Communications Systems":
                print "===========Communications Systems==========="
                print "error: 'comm_link' missing in directories"
                exit(0)
            return Comm_system.run #this is where I want to return the 
                                                   #the other file

the_game = jpark_mainframe()
the_game.mainframe_home()

I want to return a function called run() from a class in another file. When I import the file, it first runs the class with run() in it, then proceeds to run the original code. Why does this happen?

Here is the code from comm_system:

#communication systems


from sys import exit

class Comm_system(object):
def run(self):

    comm_directory = ["net_link", "tsfa_run", "j_link"]
    print "When the system rebooted, some files necessary for"
    print "communicating with the mainland got lost in the directory."
    print "The files were poorly labeled as a result of sloppy"
    print "programming on the staff's part. You must locate the"
    print "the file and contact the rescue team before the dinosaurs"
    print "surround the visitor's center. You were also notified the"
    print "generators were shorting out, and the mainframe will lose"
    print "power at any moment. Which directory will you search in?"
    print "you don't have much time! Option 1: cd /comm_sys/file"
    print "Option 2: cd /comm_sys/dis"
    print "Option 3: cd /comm_sys/comm"

    dir_choice = raw_input("jpark_edwin$ ")

    if dir_choice == "/comm_sys/file" or dir_choice == "/comm_sys/dis":
        print "misc.txt" 
        print "You couldn't locate the file!"
        print "The system lost power and your computer shut down on you!"
        print "You will not be able to reach the mainland until the system"
        print "comes back online, and it will be too late by then."
        return 'death'

    if dir_choice == "/comm_sys/comm":
        comm_directory.append("comm_link")
        print comm_directory
        print "You found the right file and activated it!"
        print "Just in time too, because the computers shut down on you."
        print "The phonelines are radios are still online."
        print "You and the other survivors quickly call the mainlane"
        print "and help is on the way. You all run to the roof and wait"
        print "until the helocopter picks you up. You win!"
a_game = Comm_system()
a_game.run()
MTT
  • 5,113
  • 7
  • 35
  • 61
Capkutay
  • 919
  • 2
  • 7
  • 10
  • Please show what's in the other file. And have you read [this](http://docs.python.org/tutorial/modules.html)? – jtbandes Jul 20 '11 at 04:59
  • This shouldn't even parse -- your indentation is wrong and even the casing differs from one place to another. – Chris Eberle Jul 20 '11 at 05:13
  • It runs, i added a couple indents by mistake when copying from textmate. fixed it in the last edit – Capkutay Jul 20 '11 at 05:30
  • As literally asked, the question is a duplicate. But as answered, it doesn't make any sense. "it first runs the class with run() in it, then proceeds to run the original code." isn't clear (classes don't "run"); and the code isn't properly indented (even after the supposed fixes); and the apparent actual **problem** is completely unrelated (preventing top-level code from running when imported). Which actually is a different duplicate. In sum, this question is not useful as a canonical, and in fact doesn't meet quality standards at all. – Karl Knechtel Aug 29 '22 at 03:48
  • As i interpret this question those other questions are *not* duplicates. In fact I am looking for the answer and it is not to be found either here or in those other ones. I am looking for `from pkga.pkgb.pkgc.ClassD import classd_method1, classd_method2`. I kinda doubt it's possible but it's not addressed in these questions/answers – WestCoastProjects Feb 13 '23 at 13:39

6 Answers6

114
from otherfile import TheClass
theclass = TheClass()
# if you want to return the output of run
return theclass.run()  
# if you want to return run itself to be used later
return theclass.run

Change the end of comm system to:

if __name__ == '__main__':
    a_game = Comm_system()
    a_game.run()

It's those lines being always run that are causing it to be run when imported as well as when executed.

agf
  • 171,228
  • 44
  • 289
  • 238
  • so i have to put an instance of the class in the original file (jurassicpark mainframe)? got it, i'll give it a try... – Capkutay Jul 20 '11 at 05:10
  • by the way, please excuse the geeky subject of this program, i couldnt really think of anything else to do – Capkutay Jul 20 '11 at 05:11
  • Check out my edit -- you need to only do the last two lines of your module if it's what's being executed directly. – agf Jul 20 '11 at 05:30
  • Oh very nice. It executes the 'Jpark_mainframe' function how I wanted. However, it doesn't return the run() function from the Comm_system class. – Capkutay Jul 20 '11 at 05:42
  • Oh do I still need an instance of Comm_system class in the 'Jpark_mainframe' class? let me try that – Capkutay Jul 20 '11 at 05:45
  • 1
    To return the run function where you have `return Comm_system.run`? Get rid of the `exit(0)` and replace `return Comm_system.run` with `return Comm_system().run()` if you want the OUTPUT from the run function, or `return Comm_system().run` if you want the function itself to use later. You need `Comm_system()` instead of `Comm_system` because you need an instance of the class, not the class itself, the way you currently have the class written. – agf Jul 20 '11 at 05:47
13
from FOLDER_NAME import FILENAME
from FILENAME import CLASS_NAME FUNCTION_NAME

FILENAME is w/o the suffix

Alon Kogan
  • 3,258
  • 1
  • 21
  • 20
4

First you need to make sure if both of your files are in the same working directory. Next, you can import the whole file. For example,

import myClass

or you can import the entire class and entire functions from the file. For example,

from myClass import

Finally, you need to create an instance of the class from the original file and call the instance objects.

bool.dev
  • 17,508
  • 5
  • 69
  • 93
Desta Haileselassie Hagos
  • 23,140
  • 7
  • 48
  • 53
4

If, like me, you want to make a function pack or something that people can download then it's very simple. Just write your function in a python file and save it as the name you want IN YOUR PYTHON DIRECTORY. Now, in your script where you want to use this, you type:

from FILE NAME import FUNCTION NAME

Note - the parts in capital letters are where you type the file name and function name.

Now you just use your function however it was meant to be.

Example:

FUNCTION SCRIPT - saved at C:\Python27 as function_choose.py

def choose(a):
  from random import randint
  b = randint(0, len(a) - 1)
  c = a[b]
  return(c)

SCRIPT USING FUNCTION - saved wherever

from function_choose import choose
list_a = ["dog", "cat", "chicken"]
print(choose(list_a))

OUTPUT WILL BE DOG, CAT, OR CHICKEN

Hoped this helped, now you can create function packs for download!

--------------------------------This is for Python 2.7-------------------------------------

James Hood
  • 43
  • 2
0

It would really help if you'd include the code that's not working (from the 'other' file), but I suspect you could do what you want with a healthy dose of the 'eval' function.

For example:

def run():
    print "this does nothing"

def chooser():
    return "run"

def main():
    '''works just like:
    run()'''
    eval(chooser())()

The chooser returns the name of the function to execute, eval then turns a string into actual code to be executed in-place, and the parentheses finish off the function call.

mikebabcock
  • 791
  • 1
  • 7
  • 20
  • You have an extra single quote making your program have a syntax error. Also, I don't think he needs `eval` for what he's doing, probably just `getattr(module_or_class, chooser())` if you're interpreting his question correctly. – agf Jul 20 '11 at 05:17
  • I can think of a half dozen ways to do what I think he wants to do, some less pythonesque than others. However 'eval' is brutally easy to work with albeit sometimes very dangerous. Its quite possible he simply needs to return an instance of a class to another file and run the function from there as you suggested. More detail would be great. – mikebabcock Jul 20 '11 at 05:25
-3

You can use the below syntax -

from FolderName.FileName import Classname
ADyson
  • 57,178
  • 14
  • 51
  • 63
Apoorva Agrawal
  • 111
  • 1
  • 3