Python import class from other files - python

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

Related

ModuleNotFoundError: I can't import custom modules properly

below the folder structure of my software:
below the code of all the .py files:
run.py:
import modules.module_01.aa as a
a.test()
# test:
if __name__=="__main__":
pass
aa.py (module 1):
import libraries.qq as q
import libraries.zz as z
def test():
q.qq_fun()
z.zz_fun()
print("ciao")
qq.py (library used by aa.py):
def qq_fun():
pass
zz.py (library used by aa.py):
def zz_fun():
pass
my question is really simple, why when I run "run.py" Python say to me:
why "aa.py" can't import the module "qq.py" and "zz.py"? how can I fix this issue?
run.py
In run.py, the Python interpreter thinks you're trying to import module_01.aa from a module named module. To import aa.py, you'll need to add this code to the top of your file, which adds the directory aa.py is in to the system path, and change your import statement to import aa as a.
import sys
sys.path.insert(0, "./modules/module_01/")
aa.py
The same problem occurs in aa.py. To fix the problem in this file, you'll need to add this code to the top of aa.py, which adds the directory qq.py and zz.py are in, and remove the libraries. from both of your import statements.
import sys
sys.path.insert(0, "./modules/module_01/libraries")

How do I import all functions from a package in python?

I have a directory as such:
python_scripts/
test.py
simupy/
__init__.py
info.py
blk.py
'blk.py' and 'info.py are modules that contains several functions, one of which is the function 'blk_func(para)'.
Within '__init__.py' I have included the following code:
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
file_lst = os.listdir(dir_path)
filename_lst = list(filter(lambda x: x[-3:]=='.py', file_lst))
filename_lst = list(map(lambda x: x[:-3], filename_lst))
filename_lst.remove('__init__')
__all__ = filename_lst.copy()
I would like to access the function 'blk_func(para)', as well as all other functions inside the package, within 'test.py'. Thus I import the package by putting the following line of code in 'test.py':
from simupy import*
However, inorder to use the function, I still have to do the following:
value = blk.blk_func(val_param)
How do I import the package simupy, such that I can directly access the function in 'test.py' by just calling the function name? i.e.
value = blk_func(val_para)
Pretty easy
__init__.py:
from simupy.blk import *
from simupy.info import *
Btw, just my two cents but it looks like you want to import your package's functions in __init__.py but perform actions in __main__.py.
Like
__init__.py:
from simupy.blk import *
from simupy.info import *
__main__.py:
from simupy import *
# your code
dir_path = ....
It's the most pythonic way to do. After that you will be able to:
Run your script as a proper Python module: python -m simupy
Use your module as library: import simupy; print(simupy.bar())
Import only a specific package / function: from simupy.info import bar.
For me it's part of the beauty of Python..

Module undefined after importing it in a function

I'm trying to use a function called start to set up my enviroment in python. The function imports os.
After I run the function and do the following
os.listdir(simdir+"main")
I get a error that says os not defined
code
>>> def setup ():
import os.path
import shutil
simdir="e:\\"
maindir="c:\\backup\\bitcois\\test exit\\"
>>> setup()
>>> os.listdir(simdir+"main")
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
os.listdir(simdir+"main")
NameError: name 'os' is not defined
The import statement is scoped. When importing modules they are defined for the local namespace.
From the documentation:
Import statements are executed in two steps: (1) find a module, and initialize it if necessary; (2) define a name or names in the local namespace (of the scope where the import statement occurs). [...]
So in your case the os package is only defined within function setup.
You are getting this error because you are NOT importing the whole os library but just the os.path module. In this way, the other resources at the os library are not made available for your use.
In order to be able to use the os.listdir method, you need to either import it alongside the os.path like this:
>>> def setup ():
import os.path, os.listdir
import shutil
simdir="e:\\"
maindir="c:\\backup\\bitcois\\test exit\\"
or import the full library:
>>> def setup ():
import os
import shutil
simdir="e:\\"
maindir="c:\\backup\\bitcois\\test exit\\"
You can read more here:
https://docs.python.org/2/tutorial/modules.html
try:
import os.path
import shutil
import glob
def setup ():
global simdir
simdir="e:\\"
maindir="c:\\backup\\bitcois\\test exit\\"
setup()
os.listdir(simdir+"main")
You need to return the paths and assign the returned values in the global scope. Also, import os too:
import os
def setup():
# retain existing code
return simdir, maindir
simdir, maindir = setup()
When you import os or do any sort of command within a function, the command's effect only last while that function itself is running. What you need to do is
import os
...Do your function and other code
This way, your import lasts for the whole program :).

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

how to run a code in __init__.py

In src/webprofiles/__init__.py I have
def match(string)
Now how can I make a call to this match from `src/python.py, which contains
from webprofiles import *
for x in text
a= webprofiles.match(x)
Its giving me an error
NameError: global name 'webprofiles' is not defined
When you use from import form, you must call function without module prefix.
just call the functions and attributes via their names.
from webprofiles import *
for x in text:
a= match(x)
but i suggest to DO NOT use wildcard('*') imports.
use this instead:
from webprofiles import match
for x in text:
a= match(x)
The syntax from x impoort * means that everything will be imported, in effect, into the global namespace. What you want is either import webprofiles followed by webprofiles.match or from webprofiles import * followed by a call to plain match
Just import webprofiles, not *:
import webprofiles
for x in text
a = webprofiles.match(x)
What you have there seems to me 2 files and you want to run a file which imports the methods contained in an other file:
import /webprofiles/init
init.match(x)
after modifiying your question:
import /webprofiles/__init__
__init__.match(x)
btw when you import something:
import my_file #(file.py)
my_file.quick_sort(x)
^^^^^^ you have to call myfile as you call normally an object
from my_file import *
#that is read as from my_file import everything
#so now you can use the method quick_sort() without calling my_file
quick_sort(x)

Categories

Resources