Importing a function from a class in another file? [duplicate] - python

This question already has answers here:
How do I import other Python files?
(23 answers)
Why is Python running my module when I import it, and how do I stop it?
(12 answers)
Closed 6 months ago.
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()

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.

from FOLDER_NAME import FILENAME
from FILENAME import CLASS_NAME FUNCTION_NAME
FILENAME is w/o the suffix

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.

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

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.

You can use the below syntax -
from FolderName.FileName import Classname

Related

Why is request module closing after giving an input?

I am working on a project that finds if a user is available or not on Instagram, (Basically that's only one of the functions.)
To do that I use this code from requests:
def start():
clear() # Clears the previous input through the OS module
print(inp + cut + "Stress them is booting...") # Inp + Cut are optional strings
use = input("Who do you want to attack? Enter here: >> ") # We take the input from here (Specifically the user)
response = requests.get("https://www.instagram.com/"+xuse+"/") # Check if the user exists, this does not work if you put # in the beginning.
if response.status_code == 404 :
PrintFatalError("User could not be found, try again.") # The user wasn't found
# Here the program stops and returns to the main program / input where I ask the user for a command.
elif response.status_code == 200 :
PrintFatalError("User " + use + " has been detected ! Proceed with the tool? ") # The user was found
f = input(" ") # This is the point
if f in "y":
print ("Beginning")
else:
print("Not a valid option, aborting.") # I abort since I don't want a loop in this phase.
Some other info that might help:
The program is fully CLI, I don't use a GUI.
This program uses while loops instead of for loops, for many reasons.
NOTE: PrintFatalError is a variable I created to display messages in red / green color. It still does not work with the classic print("string") way through.

Module urllib.request not getting data

I am trying to test this demo program from lynda using Python 3. I am using Pycharm as my IDE. I already added and installed the request package, but when I run the program, it runs cleanly and shows a message "Process finished with exit code 0", but does not show any output from print statement. Where am I going wrong ?
import urllib.request # instead of urllib2 like in Python 2.7
import json
def printResults(data):
# Use the json module to load the string data into a dictionary
theJSON = json.loads(data)
# now we can access the contents of the JSON like any other Python object
if "title" in theJSON["metadata"]:
print(theJSON["metadata"]["title"])
# output the number of events, plus the magnitude and each event name
count = theJSON["metadata"]["count"];
print(str(count) + " events recorded")
# for each event, print the place where it occurred
for i in theJSON["features"]:
print(i["properties"]["place"])
# print the events that only have a magnitude greater than 4
for i in theJSON["features"]:
if i["properties"]["mag"] >= 4.0:
print("%2.1f" % i["properties"]["mag"], i["properties"]["place"])
# print only the events where at least 1 person reported feeling something
print("Events that were felt:")
for i in theJSON["features"]:
feltReports = i["properties"]["felt"]
if feltReports != None:
if feltReports > 0:
print("%2.1f" % i["properties"]["mag"], i["properties"]["place"], " reported " + str(feltReports) + " times")
# Open the URL and read the data
urlData = "http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_day.geojson"
webUrl = urllib.request.urlopen(urlData)
print(webUrl.getcode())
if webUrl.getcode() == 200:
data = webUrl.read()
data = data.decode("utf-8") # in Python 3.x we need to explicitly decode the response to a string
# print out our customized results
printResults(data)
else:
print("Received an error from server, cannot retrieve results " + str(webUrl.getcode()))
Not sure if you left this out on purpose, but this script isn't actually executing any code beyond the imports and function definition. Assuming you didn't leave it out on purpose, you would need the following at the end of your file.
if __name__ == '__main__':
data = "" # your data
printResults(data)
The check on __name__ equaling "__main__" is just so your code is only executing when the file is explicitly run. To always run your printResults(data) function when the file is accessed (like, say, if its imported into another module) you could just call it at the bottom of your file like so:
data = "" # your data
printResults(data)
I had to restart the IDE after installing the module. I just realized and tried it now with "Run as Admin". Strangely seems to work now.But not sure if it was a temp error, since even without restart, it was able to detect the module and its methods.
Your comments re: having to restart your IDE makes me think that pycharm might not automatically detect newly installed python packages. This SO answer seems to offer a solution.
SO answer

How to acces input() function while input() is on going

I have a program that comminucate with user. I'm taking data from user with input() but, I want to tell user, for example if user typing a swearword, I want to print You are swearing! Delete it immediately! while user is typing.
As you know, firstly Python is waiting for until input() is done. My goal is access to input() before it's done then I can print You are swearing! Delete it immediately! while user typing.
There is too many dicts and functions in my program so I'm going to write an example that relevant about my main problem.
print ("Let's talk..")
isim=input("What's your name?: ")
print ("Hi there {}.".format(isim))
no=["badwords","morebadwords"]
while True:
user=input(u">>>{}: ".format(isim)).lower()
for ct in user.split():
if ct in no:
print ("You are swearing! Delete it immediately! ")
But it's not working because Python is waiting first until user input is done. How can I do this while user is typing? -Python 3.4, Windows-
I don't have much experience in this, you probably can find some package to do what you want.
But in general, you need to implement some line editing and while implementing it scan the input.
The idea of the getch function is to enable you to get callback after each key press. The code is cross platform between unix and windows.
To use it, just import getch from getch.
With limited support only to backspace, you can write something like this:
from getch import getch
import sys
def is_bad(text):
no=["badwords","morebadwords"]
words = text.split()
for w in words:
if w in no:
return True
return False
def main():
print 'Enter something'
text = ''
sys.stdout.write('')
while True:
ch = getch()
if ord(ch) == 13:
sys.stdout.write('\n')
break
if ord(ch) == 127:
if text:
text = text[:-1]
# first one to delete, so we add spaces
sys.stdout.write('\r' + text + ' ')
sys.stdout.write('\r' + text)
else:
text += ch
sys.stdout.write(ch)
if is_bad(text):
print 'You are writing something bad...'
print 'text = %s' % text
if __name__ == '__main__':
main()
The code should be improved by splitting to clearer functions and you should also handle the after bad message typing, but I hope you get the idea.
Hope it would help.

How would I separate my Python File to multiple plugins?

So first thing I want to say: I have been looking into modules and such, I just don't quiet know how I would rewrite it to fit this in.
Project: What I have is a Skype Bot using the Skype4Py module. I have about 11 commands I noticed the one script is getting a little large.
I'm trying to think about how to link one main.py file to a Plugin Folder, which contains each and every bot function in it's own respectable Python file. It sounds simple an all, except when it comes to how the function is called.
Here is just a basic look at my Skype bot, missing some of the larger functions.
import Skype4Py, random
class SkypeBot():
def __init__(self):
self.skype = Skype4Py.Skype()
if self.skype.Client.IsRunning == False:
self.skype.Client.Start()
self.skype.Attach()
self.results = ['Yes', 'No', 'Maybe', 'Never']
def main(self):
print ' Skype Bot currently running on user: %s' % self.skype.CurrentUserHandle
print "\n\nCommands Called:\n"
while True:
self.skype.OnMessageStatus = self.RunFunction
def RunFunction(self, Message, Status):
if Status == 'SENT' or Status == 'RECEIVED':
cmd = Message.Body.split(' ')[0]
if cmd in self.functions.keys():
self.context = Message
self.caller = self.context.FromHandle
self.functions[cmd](self)
def ping(self):
print " %s : Ping" % self.caller
self.context.Chat.SendMessage('Pong')
def say(self):
try:
response = self.context.Body.split(' ', 1)
if response[1] == "-info":
print " %s : say -info" % self.caller
self.context.Chat.SendMessage("Resends the message entered. \n"
"Usage: !say Hello. \n"
"Example: Bot: Hello.")
else:
say = response[1]
print " %s : Say [%s]" % (self.caller, say)
self.context.Chat.SendMessage(say)
except:
self.context.Chat.SendMessage("Please use -info to properly use the !say command")
def eightball(self):
try:
question = self.context.Body.split(' ', 1)
if question[1] == "-info":
print " %s : 8Ball -info" % self.caller
self.context.Chat.SendMessage("Responds with an answer.\n"
"Usage: !8ball 'Do I have swag?'\n"
"Example: !8Ball Response: 'Yes'")
else:
random.shuffle(self.results)
answer = self.results[3]
print " %s : 8Ball [%s]" % (self.caller, question[1])
self.context.Chat.SendMessage("!8Ball Response: %s" % answer)
except:
self.context.Chat.SendMessage("Please use -info to properly use the !8ball command")
#FUNCTIONS LIST
#********************
functions = {
"!ping": ping,
"!say": say,
"!8ball": eightball,
}
if __name__ == "__main__":
snayer = SkypeBot()
snayer.main()
So basically, what I am wondering, how can I change
self.skype.OnMessageStatus = self.RunFunction
so that it'll run functions from another file?
For a program of this size it's not really necessary to put your command functions into separate files, but I guess it is good organization. And good practice for when you write a program that has thousands of lines of code. :)
One way to do this is to create a basic SkypeBot class without any command methods and then import the command methods from your plugins directory and add them to the class. It's easy enough to add new attributes to an existing class, and it doesn't matter if the new attributes are properties or methods, the syntax to add them is identical. (With a tiny bit more work it's even possible to add new attributes to an instance, so you can have multiple instances, each with their own individual set of commands. But I guess that's not necessary here, since a program that uses the SkypeBot class will normally only create a single instance).
So we can break your question into two parts:
How to add methods to an existing class.
How to import those methods
from other source files.
As I said, 1) is easy. 2) is quite easy as well, but I've never done it before, so I had to do a little bit of research and testing, and I can't promise that what I've done is best practice, but it works. :)
I don't know much about Skype, and I don't have that Skype4Py module, and as you said, the code above is not the complete program, so I've written some fairly simple code to illustrate the process of adding plugin methods from separate files to an existing class.
The name of the main program is "plugin_demo.py". To keep things neat, it lives in its own directory, "plugintest/", which you should create somewhere in your Python path (eg where you normally keep your Python programs). This path must be specified in your PYTHONPATH environment variable.
"plugintest/" has the following structure:
plugintest/
__init__.py
plugin_demo.py
plugins/
__init__.py
add.py
multiply.py
The __init__.py files are used by Python's import machinery to let it know that a directory contains a Python package, see 6.4. Packages in the Python docs for further details.
Here are the contents of those files. Firstly, the files that go into "plugintest/" itself:
__init__.py
__all__ = ['plugin_demo', 'plugins']
from plugintest import *
plugin_demo.py
#! /usr/bin/env python
#A simple class that will get methods added later from plugins directory
class Test(object):
def __init__(self, data):
self.data = data
def add_plugins(cls):
import plugins
print "Adding plugin methods to %s class" % cls.__name__
for name in plugins.__all__:
print name
plug = getattr(plugins, name)
print plug
method = getattr(plug, name)
print method
setattr(cls, name, method)
print
print "Done\n"
add_plugins(Test)
def main():
#Now test it!
t = Test([1, 2, 3]); print t.data
t.multiply(10); print t.data
t.add(5); print t.data
if __name__ == '__main__':
main()
And now the contents of the "plugintest/plugins/" directory:
__init__.py
__all__ = ['add', 'multiply']
from plugintest.plugins import *
add.py
#A method for the Test class of plugin_demo.py
def add(self, m):
self.data = [m + i for i in self.data]
multiply.py
#A method for the Test class of plugin_demo.py
def multiply(self, m):
self.data = [m * i for i in self.data]
If you cd to the directory containing the "plugintest/" folder, you should be able to run it with
python plugintest/plugin_demo.py
and if you cd to "plugintest/" itself
python plugin_demo.py
Also, in the interpreter (or another Python program), you should be able to do
import plugintest
and then run the main() function of "plugin_demo.py" with
plugintest.plugin_demo.main()
The other usual variations of from ... import ... etc should also work as expected.
The function in "plugin_demo.py" that performs the magic of adding the imported methods to the Test class is add_plugins(). When it runs it prints out each method name, its module, and its function. This could be handy during development, but you'd probably comment out some of those print statements once the program's working properly.
I hope this helps, and if you have any questions please don't hesitate to ask.

Python Precommit hook, Looking at lines for some text

Hello, my question is regarding a Python script I am trying to get to work. The point of this is that when someone makes a SVN Commit they see a login template with four lines: Branch, Bug_Number, Feature affected and Overview. Now I am trying to write a script to make sure that they wrote something on it to make sure no one enters a empty log to commit.
Here is what I have so far in python its based on a old python script.
print "Importing the items"
import re
import sys
import os
print "Initializing the list."
argsList = []
hndFile = open(sys.argv[1],"r")
for line in hndFile:
argsList.append(line)
hndFile.close()
print "Checking what is blank"
faOK = ovOK = False
for line in argsList:
line = line.strip()
if line.startswith('FEATURE_AFFECTED:'):
faOK = line[17:] != ''
if line.startswith('OVERVIEW:'):
ovOK = line[9:] != ''
if not faOK:
print "You Must Enter the Feature Affected"
ret = -1
elif not ovOK:
print "You Must Enter an Overview of the Fix"
ret = -1
else:
ret = 0
print "Finishing the script"
sys.exit(ret)
Any advice would help. I am using Windows XP and currently nothing is happening. I am also using collabnet svn. Currently nothing is happening when I try to run this script. I know I haven't added svnlook in the script I cant really think of where to add and for the variable for it. Thank you.

Categories