os.path.isfile fails when using sys.path.append - python-3.x

I have the following:
application/3rdPArtyApp/file.py
application/3rdPArtyApp/directory/someFile
application/MyApp/file.py
I want to access files from 3rdPArtyApp from MyApp so I do the following in MyApp/file.py
sys.path.append('../3rdPArtyApp')
This works fine and I can now access the files and functions by importing them.
However, there is a file in 3rdPartyApp that attempts to access a file inside a folder directory/someFile.
It uses the following to check if its a file which fails whenever its called from MyApp but doesn't fail when its called stand alone from 3rdPartyApp.
os.path.isfile(file)
I am assuming if fails when called from MyApp because its expecting it to beunder MyApp path.
How can I solve this issue?

If you cannot change the library code, I think you are stuck with having to change the working directory before every call.
I therefore implemented this function-like helper class change_cwd. Just wrap every function call to the external library with with change_cwd('../3rdPArtyApp'):.
import os
class change_cwd:
def __init__(self, path):
self.path = os.path.abspath(path)
def __enter__(self):
self.old_cwd = os.getcwd()
os.chdir(self.path)
def __exit__(self, exc_type, exc_value, traceback):
os.chdir(self.old_cwd)
print(os.getcwd())
with change_cwd('Downloads'):
print(os.getcwd())
print(os.getcwd())
/home/<user>
/home/<user>/Downloads
/home/<user>

Related

Python class cannot open file when object is created from directory below

I have a app.py file which is using a custom class which I created one level below, ie.
from myfolder import util_file
def get_data():
dataContainer = util_file.MyDataContainer()
# do more stuff
One folder down my util_file I create MyDataContainer as a class that uses data from two local files to instantiate itself. ie.
class MyDataContainer:
def __init__(self):
with open('file1.txt', 'r'):
#get needed init data part 1
#repeat operation with data in file2.txt
The object is created fine when I run from the file itself, ie.
if __name__ == '__main__':
testcont = MyDataContainer()
The issue is that when I run the code in app.py I get:
FileNotFoundError: [Errno 2] No such file or directory: 'file1.txt'
thrown at the line
with open('file1.txt', 'r'):
I am guessing that python is unable to see the file1.txt and file2.txt since it is in another directory at runtime but I checked the my path and the subfolder is in sys.path at runtime, so I believe these should be visible. I really do not understand what is going on here. Is there a different reason python is unable to see these files?

How can I fix a very basic ImportError in Python3?

Similar to ImportError: Cannot import name X, I have a main.py file and, in the same folder, a few other python files bill.py and flatmate.py.
bill.py and flatmate.py each contain classes, nothing more.
Directory structure:
parentfolder
- main.py
- bill.py
- flatmate.py
- files
- pic.png
- doc.pdf
Sample code:
main.py:
import bill # won't work
from flatmate import Flatmate # won't work
...
bill.py:
class Bill:
def __init__(self, ...):
...
flatmate.py:
class Flatmate:
def __init__(self, ...):
...
I get an ImportError: cannot import name 'Bill' from 'bill' (c:\Users\lavid\Desktop\Python Experimente\Python OOP Kurs\App-2-Flatmates-Bill\bill.py). I am pretty sure I don't have circular references. What could be the cause of this problem?
Make sure that all files are next each others
try:
from . import module
if this doesn't work , add your files dir to the Question
Saving the referenced files before accessing them helped a lot.

Python import files from 3 layers

I have the following file structure
home/user/app.py
home/user/content/resource.py
home/user/content/call1.py
home/user/content/call2.py
I have imported resources.py in app.py as below:
import content.resource
Also, I have imported call1 and call2 in resource.py
import call1
import call2
The requirement is to run two tests individually.
run app.py
run resource.py
When I run app.py, it says cannot find call1 and call2.
When run resource.py, the file is running without any issues. How to run app.py python file to call import functions in resource.py and also call1.py and call2.py files?
All the 4 files having __init__ main function.
In your __init__ files, just create a list like this for each init, so for your user __init__: __all__ = ["app", "content"]
And for your content __init__: __all__ = ["resource", "call1", "call2"]
First try: export PYTHONPATH=/home/user<-- Make sure this is the correct absolute path.
If that doesn't solve the issue, try adding content to the path as well.
try: export PYTHONPATH=/home/user/:/home/user/content/
This should definitely work.
You will then import like so:
import user.app
import user.content.resource
NOTE
Whatever you want to use, you must import in every file. Don't bother importing in __init__. Just mention whatever modules that __init__ includes by doing __all__ = []
You have to import call1 and call2 in app.py if you want to call them there.

How to get debug output for Jupyter Notebook ContentManager code

I'm writing a ContentsManager for Jupyter-Notebook to store data on a local OpenStack SwiftStore. I'm taking S3Contents as my starting point.
I have a basic framework that will connect & create a container if it doesn't exist.... however before I go any further, I need to start creating unit tests.
My question is how do I see the DEBUG output?
If I have a method that starts:
def get(self, path, content=True, type=None, format=None):
"""Retrieve an object from the store, named in 'path'
"""
self.log.debug("SwiftContents[swiftmanager]: get '%s', path)
.... how do I see the output SwiftContents[swiftmanager]: get '\foo\bar'?
Also, what's the testing framework used by notebooks?
class SwiftContentsManager(ContentsManager):
# Initialise the instance
def __init__(self, *args, **kwargs):
super(SwiftContentsManager, self).__init__(*args, **kwargs)
self.swiftfs = SwiftFS(log=self.log)
It looks a bit like unittest, except it has setUp rather than startUp
To run tests: nosetests path/to/tests/test_foo.py
To run tests, and see what it's actually doing: nosetests -v path/to/tests/test_foo.py
To run tests, see what it's actually doing, and see the debug output: nosetests -v --debug path/to/tests/test_foo.py
For more information, see http://pythontesting.net/framework/nose/nose-introduction/

pyinstaller "could not parse stylesheet"

I'm building a small program using pyQt and pyInstaller.
I've tried to add an background image to my QMainWindow:
class pyPrimaMainWindow(QMainWindow):
def __init__(self):
...do some stuff...
self.setWindowIcon(QIcon(os.path.join(self.py_prima.resource_path(), "TH.ico"))) # <- this works
self.setStyleSheet("QMainWindow{{border-image: url({0});background-size:100%;}}".format(os.path.join(self.py_prima.resource_path(), "bg.png")))
The resource_path() methods looks like that:
def resource_path(self):
""" Get absolute path to resource, works for dev and for PyInstaller """
# PyInstaller creates a temp folder and stores path in _MEIPASS
base_path = getattr(sys, '_MEIPASS', "C:/Users/Tobias/eclipse/workspace/PyPrima/data/")
# except Exception:
# base_path =
print(base_path)
return base_path
It's copied from the pyinstaller wiki, returns an absoulte path and works for other pictures/icons.
However, if I build an executable with pyInstaller, the programm runs nice, but the background image is missing. Instead, the console outputs
"could not parse stylesheet of object ..."
If I run the python file, it works all fine...
Any ideas on this?
Thanks!
I'll answer my own question just in case someone else stumbles upon the same problem.
The fileseparators are wrong...
Fix it with
bgpath = os.path.join(self.py_prima.resource_path(), "bg.png")
bgpath = bgpath.replace("\\", "/")
self.setStyleSheet("QMainWindow{{border-image: url({0});background-size: 100%;}}".format(
bgpath))

Resources