Can't import functions/modules - python

I'm simply trying to import a function from another script. But despite import running successfully, the functions never enter my local environment.
The paths and files look like this:
project/__main__.py
project/script_a.py
from setup import script_b
x = ABC() # NameError: name 'ABC' is not defined
print(x)
project/setup/__init__.py
project/setup/script_b.py
def ABC():
return "ABC"
I've done this before and the documentation (officials and on here) is quite straightforward but I cannot grasp what I am failing to understand. Is the function running but never entering my environment?
I also tried using...
if __name__ == '__main__':
def ABC():
return "ABC"
...as script_b.

Import the functions inside the module:
from setup.script_b import ABC
Or call the function on the modules name like said in the comments
x = script_b.ABC()

Related

import output of command instead of a file - python

I have a very simple script that i wish to test out.
Master script (caller.py):
#!/usr/bin/env python2.7
import test2
test2.printMe()
Function/Module Script (test2.py):
def printMe():
print 'this actually works'
When I run caller.py, it works. Because the test2.py script exists in the same directory from which I'm calling caller.py.
What happens if i need to make the function(s) defined in test2.py available to the caller.py script, through a variable? There are times when the content of the test2.py function script wont always be in a file. Sometimes, it's inside a variable.
So basically, im looking for a way to access the functions that are in a variable just as import would access functions that are in a file.
I wish to be able to do something like this:
from commands import *
def run_command(cmd):
status, text = getstatusoutput(cmd)
print text
run_command('python /tmp/test2.py')
test2.printMe()
Please advise.
Try this:
from sys import path as sys_path
from os import path
def import_module(path_to_py_file):
dir_name, module_name = path.split(path.splitext(path_to_py_file)[0])
sys_path.append(dir_name)
return __import__(module_name)
Now you can do this:
test2 = import_module(r'/tmp/test2.py')
test2.printMe()

Python import class from other files

I have three files under the same directory, namely, main.py, Newtester.py, and fileUtility.py. In Newtester.py there is a class named Function. In main.py, there are the following codes:
from file.py import *
...
def main():
...
funcs = parseFuncSpec(funcInputFile)
parseFuncSpec is defined in fileUtilities.py as:
some code to import Newtester.py
def parseFuncSpec(fName):
curFunc = function(funcName, numTest, [], score)
Regardless of what I put in import Newtester.py, I always get an error saying "Function" (the class defined in the file "Newtester.py") is not defined. Following Python: How to import other Python files, I have attempted
import Newtester
__import__("Newtester")
exec("Newtester.py")
exec("Newtester")
import importlib
importlib.__import__("Newtester")
os.system("Newtester.py")
But none of them seemed to work. Any advice is appreciated. See https://github.com/r2dong/unitTesting if you are interested in seeing the complete files.
It's because you are not using it correctly
well when you use import statement like below only Newstester file is imported
import Newtester
hence instead of using parseFuncSpec() directly you have to use it as Newtester.parseFuncSpec()
or to use parseFuncSpec() directly you need to use below import statement:
from Newtester import parseFuncSpec

Python Creating and Importing Modules

I wrote functions that are applyRules(ch), processString(Oldstr) and named it lsystems.py
And I put
import lsystems
def main():
inst = applyRules("F")
print(inst)
main()
and saved it as mainfunctioni
However, when I try to run mainfunctioni, it says 'applyRules' is not defined.
Doesn't it work because I put import lsystems?
What should I do to work my mainfunctioni through lsystems?
You have to call it with module.function() format. So in this case, it should be called like as follows:
inst = lsystems.applyRules("F")
You have to access all the methods from your module with the same format. For processString(Oldstr), it should be similar.
test_string = lsystems.processString("Somestring")
When you import a module using import <module> syntax, you need to access the module's contents through its namespace, like so:
import lsystems
def main():
inst = lsystems.applyRules("F")
print(inst)
main()
Alternatively, you can directly import the function from the module:
from lsystems import applyRules
def main():
inst = applyRules("F")
print(inst)
main()

Python 3.x.x one variable spread across multiple .py files

This is not a problem with my code, but rather a general question about Python 3.
Say you had a game, which had 4 parts to it, and the first part (main.py) declares a variable
that say, part 2 needs to run itself. Would you be able to declare that variable, then import part2 (That needs the variable to run smoothly) and have the variable carry on from main.py to part2.py after importing part2.py into main.py.
If you want to use the variable once you can do this.
# part2.py
def scream():
print(sound)
# part1.py
import part2
if __name__=="__main__":
part2.sound = "Yoooo"
part2.scream()
#Output:
Yoooo
If you want to be able to change the variable later. You can create a property
Or simply do this:
# part2.py
# gvars is defined later
def scream():
print(gvars.sound)
# part1.py
import part2
class GameVariables:
pass
if __name__=="__main__":
gvars = GameVariables()
part2.gvars = gvars
gvars.sound = "Yooo"
part2.scream()
gvars.sound = "Whaa"
part2.scream()
#output
Yooo
Whaa
here is a simple example you can try out
file1.py
import sys
sys.argv = "Yellow" #probably not a really great Idea but should suffice
from file2 import sys as sys2
print "Imported argv from file2",sys2.argv
print "Same thing? ", sys is sys2
file2.py
import sys
print "My argv f2:",sys.argv

Running a function in Python if a user chooses it (EasyGui)

I'm using EasyGui to allow a user to select multiple options. Each option is a function which they can run if they select it. I'm trying to use dictionaries as suggested in other threads but I'm having trouble implementing it (Module object is not callable error). Is there something I'm missing?
from easygui import *
import emdtest1
import emdtest2
import emdtest3
EMDTestsDict = {"emdtest1":emdtest1,
"emdtest2":emdtest2,
"emdtest3":emdtest3}
def main():
test_list = UserSelect()
for i in range(len(test_list)):
if test_list[i] in EMDTestsDict.keys():
EMDTestsDict[test_list[i]]()
def UserSelect():
message = "Which EMD tests would you like to run?"
title = "EMD Test Selector"
tests = ["emdtest1",
"emdtest2",
"emdtest3"]
selected_master = multchoicebox(message, title, tests)
return selected_master
if __name__ == '__main__':
main()
You're putting modules into the dict, when you want to put functions in it. What you're doing is the equivalent of saying
import os
os()
Which, of course, makes no sense. If emdtest1, emdtest2, and emdtest3 are .py files with functions in them, you want:
from emdtest1 import function_name
Where function_name is the name of your function.
You need to import the functions rather than the module ... for example , if you have a file called emdtest1 with a defined function emdtest1, you'd use:
from emdtest1 import emdtest1

Categories

Resources