How to access code outside of current folder directory? - python

I want to access my 'utils' folder that is outside of the current directory that my code is in. How do I access the files and functions within that file?
For example, I am trying to access functions in file_to_access.py from 00_label_data.py.
I tried doing this but it still is not working and says 'no module found'
What is the correct method for doing this method?

It's a little hard to tell from the screen shots, as the display isn't quite as descriptive as I've like. However, the main suspicion is at
... import file_to_access.py
There is no such module: the module name is merely file_to_access; you supplied the file name. Also, I suspect that you will want
import mbl.code.utils.file_to_access
to properly activate your reference in line 8.

Related

Run a function when importing module in Python

What I want to achieve: I have a function (object/module/etc) that allows me to run a model. This model requires a few parameters, so I want to have them in a config file rather than pass all through the code. So what I want is to have a config file created automatically when my module is imported. Is it possible in python? Can I have some pointers on where to start please?
All the code in a python file is run when its imported. If you have
def f():
print("ran")
print("imported")
Then when you import it it will print imported
This is also why you sometimes see if __name__=="__main__":
In some files. The code in that block is only run if the file is run as main not imported.
However creating files in a predetermined location may be bad UX, so if you want other people to use your library id think of a better solution.
Generally you can just put code at top level of a module and it will run.

python modules accessing files in "local" directory

I have simple question.
I have a python module "dev1.py" that needs a file "dev1_blob"
If I have everything in one directory.
my_app loads the dev1 like
from dev1 import func1
it works fine.
I want to move dev1.py to a directory "./dev_files" with init.py in it.I can load the dev1.py as
from dev_files.dev1 import func1
However when func1 runs to access the "device_blob" -- it barfs as:
resource not found ..
This is so basic that I believe I am missing something.
I can't figure out why great minds of python want everything to refer to __file__ (cwd) and force me to modify dev1.py based on where it's being run from. i.e. in dev1.py refer to the file as: 'dev_files/device_blob'
I can make it work this way, but it's purely absurd way of writing code.
Is there a simple way to access a file next to the module files or in the tree below?
Relative pathing is one of Python's larger flaws.
For this use case, you might be able to call open('../dev_files/device_blob') to go back a dir first.
My general solution is to have a "project.py" file containing an absolute path to the project directory. Then I call open(os.path.join(PROJECT_DIR, 'dev_files', 'device_blob')).

Cannot get suggestions when importing Python file from another folder (Wing IDE)

I have a Python file called caller.py located at C:\Temp. I have two other Python files: local_testlib.py located in C:\Temp and testlib.py located in C:\Temp\MyLibs.
I am trying to import both of those files in Wing IDE Pro.
import sys
sys.path.append(r'C:\Temp\MyLibs')
import testlib #located in C:\Temp\MyLibs
import local_testlib #located in C:\Temp
#check suggestions by Wing
local_testlib. #get suggestions as list of variables etc. from the file
testlib. #don't get any suggestions
print testlib.myvar #get variable value printed OK
I get suggestions only for the local_testlib, nothing for the testlib (see picture below). I do get access to the variables in the testlib.py (so it is imported correctly) though. What adjustments should I have done to make this work?
To solve this you can add C:\Temp\MyLibs to your Python Path in Wing's Project Properties (or Configure Python dialog in Wing 101). Or in Wing Personal or Pro you can set the file as the main debug file, although I just noticed that you'll need to restart Wing before that approach works due to apparent failure to rescan the file.
This could probably be changed to take local path modifications into account in our source analysis, although in general modifying sys.path like this is not a great way to do things since the added path may screw up other modules you import later if they are trying to import a module called testlib from another location. That's why we only look for modifications like this in the main debug file.
You may want to instead make MyLibs into a package by adding a file called init.py inside it and then you can do this:
from MyLibs import testlib
That solves it w/o any extra configuration in Wing IDE.

Dynamically running python code on google app engine

I am trying to be able to dynamically run python code, with variables being able to be passed through to the code. I was able to do this on my computer before I added my project to the google app engine environment (because I can access all the files, but now, with google app engine, I can not do that.
I am struggling to find a solution to this problem. It does not need to be too terribly fancy, just send variables in and get html out, as well as scripts being able to be added client side (the crucial part) to whatever database method that is used.
Edit:
well basically what I mean by dynamically is so that I can import (or thats what I did in IDLE when I tested the prototype, the solution will probably not be called importing) a python script with the name of the library being stored in a variable, as well as an unknown number of variables that would be added. I got this to work on Idle, but now I need to get it to work in the google app engine environment, and people need to be able to upload scripts as well (which is the main problem that cascades into many more problems)
Edit:
When I say that I managed to get this to work on my local machine, I mean I was able to manually drop scripts into the same directory as my main script. The script would later import and execute the scripts when necessary. I was able to get this to work with the following code:
#calling function
mod = __import__('actions.'+folder+'.'+FILE)
VAR = getattr(getattr(mod, folder), FILE)
response = VAR.Main()
print response
This code worked on both my laptop and in the google app engine environment, But When I try to add more scripts to the directory is when things get problematic. On my laptop I could just move the file over one way or another because I had full access to the file directory. On Google App engine I do not have the ability to just upload a file to the same directory or subdirectory of the rest of my python scripts. So basically the problem comes up when trying to design a way to allow more code to come into the system (in my case, adding more 'plugins').
The answer is the exec statement (also known as the exec() function) or the eval() function. See http://docs.python.org/reference/simple_stmts.html#the-exec-statement and http://docs.python.org/library/functions.html?highlight=eval#eval. These can execute arbitrary Python code from a string. exec() runs a script and you get the side effects; eval() takes an expression and returns its value. Typically you pass input in as variables in the local namespace.
Ok, So what I eventually did was use the datastore to upload everything such as the name, description, uploader and code of the plugin (for now the code is just entered into a textarea box). I then, instead of importing a file located in a folder under the same directory of my code like I had before when running everything off of my desktop, Imported the plaintext code into a module using this little bit of magic:
#Initiating Variables for use by importing functions
module_name = 'mymod'
filename = 'action_file'
source = PossibleMatches[0][1] #the source code from the best matched option
# define module_name somewhere
import types
module = types.ModuleType(module_name)
# source should the code to execute
# filename should be a pseudo-filename that the code's from
# (it doesn't actually have to exist; it's used for error messages)
code_object = compile(source, filename, 'exec')
#execute the code in the context of the module
exec code_object in module.__dict__
#Executing the 'Main' Function from the code
return module.Main()

Python project architecture

I'm a java developer new to python. In java, you can access all classes in the same directory without having to import them.
I am trying to achieve the same behavior in python. Is this possible?
I've tried various solutions, for example by importing everything in a file which I import everywhere. That works, but I have to type myClass = rootFolder.folder2.folder3.MyClass() each time I want to access a foreign class.
Could you show me an example for how a python architecture over several directories works? Do you really have to import all the classes you need in each file?
Imagine that I'm writing a web framework. Will the users of the framework have to import everything they need in their files?
Put everything into a folder (doesn't matter the name), and make sure that that folder has a file named __init__.py (the file can be empty).
Then you can add the following line to the top of your code:
from myfolder import *
That should give you access to everything defined in that folder without needing to give the prefix each time.
You can also have multiple depths of folders like this:
from folder1.folder2 import *
Let me know if this is what you were looking for.

Categories