Python file imports using a string - python

I am trying to import a function from another python file in a different directory but only have the function name in string form. I have tried using import lib as follows:
sys.path.insert(1, file_path) # Works fine
import file # Works fine
run_function = importlib.import_module("file.function"+str(loop)) # Error occurs here
But when I try this I get the error message: ModuleNotFoundError: No module named 'file.function1'; 'file' is not a package
I have also tried doing:
from file import *
eval("function{loop}()")
But with this method I recieve the error message: SyntaxError: import * only allowed at module level
I am not sure exactly how to fix the issue or whether there would be a better way of doing this. I am open to suggestions. Thanks!

You can import anywhere in the file (obviously importing within a function would limit the module scope to the function itself).
def func(x):
for i in range(x):
eval(f"from lib import function{i}")
# All functions available in this scope
For extra safety, I recommend this be put into a try/catch.

You don't import functions. You have successfully imported the module, which includes the function, so all you have to do is get it
sys.path.insert(1, file_path) # Works fine
import file # Works fine
result = getattr(file, "function1")(loop)

Related

Python function from imported file shows as undefined

I have a moveslist.py file with function movesSelection and a main.py file. Within my main.py, I've made sure that my variables are set to global and I had another function makeNewChar. Within makeNewChar, I'm trying to call movesSelection but I get "NameError: name 'movesSelection' is not defined.
Since my moveslist.py uses some global variables from main, I imported main into the file.
For my main.py, I did from moveslist import *. I also tried import movesList and from moveslist import movesSelection. All of those threw back errors.
How can I use movesSelection within my main.py?
There may be a few different reasons but some of the most common are having a file with the same name or likely the file you are looking for is in another directory so i will show you my correct here
[Edit] You should remove the .py when importing example below
## This is "main.py" keep that in mind when viewing
## Change line 4 to import and the python file as Func = Func.py in this context
import Func
Func.Activate()
## This is "Func.py"
class Activate:(
print("Hello World!")
)
Or you may need to do as says below!
##Include file extension and move the file with the folder in the correct space and i'd appreciate it if you'd be so kind to mark this question as correct
import movesSelection.py
Add "from moveslist import movesSelection" into makeNewChar.
You do not have to add the .py suffix when you import.

`Importlib` not actually importing modules?

I'm trying run an env_setup script that imports modules used in my main_script. But despite successfully running env_setup.py the modules are not being imported (presumably it is being run in its own environment).
Previously I know I have somehow sucesfully used:
from env_setup import *
However this fails for me now.
I tried a second approach using:
importlib.util.spec_from_file_location(name, location)
But this also fails.
Below is an example of what I am attempting (using the second approach in my main_script.py):
Example env_setup.py script:
import datetime # import module
print("modules imported!!!") # confirm import
Example main_script.py script:
# This first section should import `datetime` using `env_setup.py`
import importlib
spec = importlib.util.spec_from_file_location(
name='setup',
location='/home/solebay/my project/env_setup.py' # path to `set_up` script
)
my_mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(my_mod)
# This returns "modules imported!!!"
# Here we run a basic command to check if `datetime` was imported...
now = datetime.datetime.now()
print(now.strftime('%H:%M:%S on %A, %B the %dth, %Y')) # Should print time/date
# NameError: name 'datetime' is not defined
How do I get python to actually import the required modules into the environment running main_script.py? It creates a __pycache__ folder so I know the path is correct.
After dynamically importing a module you can either access the module directly by using my_mod.function() or import everything (imitate from module import *) like so:
import sys
sys.modules["setup"] = my_mod
from setup import *
del sys.modules["setup"] # Optional
After lots of searching I decided:
from env_setup import *
Should absolutely work.
I moved my most recent scripts to a fresh directory with a simpler tree and everything works.
I'm thinking it was a bug?
Update (Not a bug):
As per the useful suggestion of Bharel I ran..
import os
os.getcwd() # Returned 'wrong' directory
os.listdir() # Returned 'wrong' listing
Visual inspection of the folder tree showed that env_setup.py was present, but this file and others were absent from the true listing returned by os.listdir().
I'm running my code through the IDE "Atom" using the "Hydrogen" module. I opened a new window, added a new project folder and ran the command again and it updated.
I'm assuming I moved a folder and Atom didn't have a chance to update the path.
End result:
from env_setup import *
Works prefectly.

Path inserted into sys.path but import module still shows error, what am I missing?

Does anyone know the proper way to import a module in a different directory?
I have used the following codes below, it works but there is still a 'no module named ...' error.
The code runs fine but I do not know how to get the import to recognise the file.
import sys
path = r'C:\Users\User\OneDrive\Documents\Programming\Python'
sys.path.insert(0, path) # insert file path to the start of the path list
import random100Numbers # Here there is a no module named warning...
print(random100Numbers.rand100Num(90)) # code executes as it is
print(random100Numbers.rand100Num(-100)) # code executes as it is

Python Searching for files and Importing them

I need to write a function that walks through directories searching for files that end in _prj.py, and then extract some lists from there. The way I'm doing it right now is by using os.path.walk and then importing. My code looks like this:
for py_file in files:
if py_file.endswith("_prj.py"):
print py_file[:-3]
module = py_file[:-3]
import module
However, I get an import error:
ImportError: No module named module
I think I understand why, I'm just not sure how I would make the import statement work. Is there a way to make the module variable be read as the file name instead of "module"?
The correct way of import a module by a String name is by using another module known as importlib
import importlib
math_module = importlib.import_module("math")
print math_module.sqrt(25)
>>> 5.0

python- os.system() not properly opening then immediately closing file

I am trying to get a python script to open another python script in a directory that I know of but the actual filename is a variable. I would like to execute this file or be able to import the file (either way would work for what I am trying to do) but I am having problems with each one.
for trying to execute it, the dos style box appears but quickly disappears, too quickyl to really do anything. I even added a Raw_Input() and executed the file on its own and got it to work. here is the like on code:
os.system("python actions/"+Script)
Script being the name of the python file in a string. I know that the file is found but the problem is that it disapears too quickly
the other way I am trying to do it is by importing the file:
import 'actions/'+Script
this is the only logical way I can think of to import the damn thing but I keep getting syntax errors
Use the __import__ function to import a module whose name isn't known until runtime:
# Import the module
mymodule = __import__('actions/' + Script)
# Call functions in the module etc.
mymodule.do_something(42);
Or try import (been around a while I believe) or importlib (added in python 2.7):
import">http://docs.python.org/library/functions.html#import
http://docs.python.org/library/importlib.html#importlib.import_module
try:
import sys
sys.path = ["./actions"] + sys.path
exec("import " + Script[-3])

Categories