Recognizing nested files within packages using Py2app - python

I have a large Python project that I am working to make to an app, using Py2app. However, my main file includes a large number of imports, which cannot all be recognized by Py2app. Here is an example of the scale of this:
from Assets.Miscellaneous.formatting import Format
from Assets.Miscellaneous.inventory import InventoryCheck
from Assets.Health_Attack.stats import Stats
from Assets.Battle_System.battle_request import Battle_Request
from Assets.Health_Attack.items import Item
from maps import Position
from Assets.Health_Attack.merchants import Merchant
from Assets.Audio.audio_control import main_audio_loop
from Assets.Health_Attack.status_screen import print_status_screen
from Assets.Health_Attack.items import all_keys
from Assets.Miscellaneous.key_door_event import check_key_inventory, pass_door
from Assets.Visuals.neo_animation_system import show_graphic
from Assets.Miscellaneous.reset_game import full_reset
from Assets.Miscellaneous.neo_2_settings import settings
from Assets.Miscellaneous.bed_check import bed_check
from Assets.Miscellaneous.window_event import window_event
Here is my setup.py file:
from setuptools import setup
import os
APP = ['adventuregame.py']
DATA_FILES = [
'print_speed.txt', 'maps_data.py', 'current_enemy_health.txt', 'first_game.txt',
'map_size.txt', 'item_inventory_data.txt',
'audio_stop_check.txt', 'savedvariables.txt', 'player_stats.txt', 'inventory_data.txt',
'curr_pl_mat.txt', 'battle_happening.txt', 'money.txt', 'curr_pr_mat.txt',
'item_tracker.txt']
for index, item in enumerate(DATA_FILES):
DATA_FILES[index] =
"/Users/caspianahlberg/Desktop/Programming/Isolated_AG/Assets/Global_Vars/" + item
setup(
app=APP,
data_files=DATA_FILES,
setup_requires=['py2app']
)
I have a large number of text files that store data relating to the game that I am making. However, when running the executable generated, this error occurs:
FileNotFoundError: [Errno 2] No such file or directory: '/Users/caspianahlberg/Desktop/Programming/Isolated_AG/dist/adventuregame.app/Contents/Resources/Assets/Global_Vars/current_enemy_health.txt'
2020-03-17 00:21:01.094 adventuregame[42211:18386951] adventuregame Error
So, the problem is that somehow, everything is not compiled in some way. This text file is in the wrong directory, which I am not sure how it happened. Please provide some help for my problem, it's really frustrating to deal with myself!

Related

Trying to reuse code across multiple Flask servers, stuck on importing with errors "ModuleNotFoundError" or "ImportError"

My goal is to import code into three separate Flask servers. It's not going well. I am on python 3.10.4. I have read perhaps 10 different posts that say things like "put a __init__.py file in your folders" which I have done.
For context I'm not exactly new to Python but I've never learned the importing/module system properly.
I have three Flask servers that run scraping operations on different (but similar) websites. I need them to be separate for various reasons. Anyway, all three need to run the same procedure of getting an IP for a proxy from my proxy provider. For this I have some code:
# we don't need the details here so I snip it to save space
def get_proxy_ip(choice):
r = requests.get(download_list, headers={"Authorization": "Token " + token})
selected_proxy_ip = r.json()["results"][choice]["proxy_address"]
selected_proxy_port = r.json()["results"][choice]["port"]
print(selected_proxy_ip)
return selected_proxy_ip, selected_proxy_port
I want to use this function across all 3 of my Flask servers. Here are some various ways I've tried to import the code into one of the Flask servers:
scrapers/rentCanada/app.py
import requests
from flask import Flask, request, make_response
print("cats")
app = Flask(__name__)
print(__name__, __package__)
# from ..shared.ipgetter import get_proxy_ip
# from ..shared.checker import check_public_ip
# from scrapers.shared.ipgetter import get_proxy_ip
# from scrapers.shared.checker import check_public_ip
import shared.ipgetter as ipgetter
import shared.checker as checker
None of them work.
import shared.ipgetter as ipgetter yields:
cats
__main__ None
Traceback (most recent call last):
File "/home/rlm/Code/canadaAps/scrapers/rentCanada/app.py", line 10, in <module>
import shared.ipgetter as ipgetter
ModuleNotFoundError: No module named 'shared'
ModuleNotFoundError: No module named 'scrapers' yields: ModuleNotFoundError: No module named 'scrapers'
from ..shared.ipgetter import get_proxy_ip yields: ImportError: attempted relative import with no known parent package
At this point you need to see my folder structure.
/scrapers
..__init__.py
..setup.py
../rentCanada
.....__init__.py
.....app.py
../rentFaster
.....__init__.py
.....app.py
../rentSeeker
.....__init__.py
.....app.py
../shared
.....__init__.py
.....ipgetter.py
.....checker.py
I need to be able to use any of the app.py files as entry points.
I also tried setup.py with this:
from setuptools import setup, find_packages
setup(
name = 'tools',
packages = find_packages(),
)
followed by python setup.py install but that didn't make a "tools" import available in app.py like I wanted.
As a final note I suspect someone will tell me to use a blueprint. To me those look like a tool I'd use if I was adding a route. I'm not sure they're right for a simple function, but maybe I'm wrong.
My solution for now is to run Flask with python rentCanada/app.py from the /scrapers folder and use this code
import sys
from pathlib import Path
sys.path.append(str(Path(__file__).parent.parent)) # necessary so util folder is available
import requests
from flask import Flask, request, make_response
print("cats")
app = Flask(__name__)
print(__name__, __package__)
from util.ipgetter import get_proxy_ip
from util.checker import check_public_ip
So the program appends the app.py file folder's parent folder to the path. That makes the util folder (which used to be shared but had a naming conflict) available within the app.py file.

Why can't Python import a file from a relative path?

I found this question helpful, but Python is unable still to find the folder.
I have a Django folder structure that looks like this:
todoproject
pythonDiscordChatbot
processLessons.py
todoapp
testChatFunctions.py
I'm trying to import a function called 'routes' into testChatFunctions.py, but I keep getting this error:
File "c:\Users\Kaij\Documents\chatSiteDjango\todoproject\todoapp\testChatFunctions.py", line 6, in <module>tSiteDjango\todoproject\todoapp\tesssLesson import *tChatFunctions.py", line 6, in <modd 'pythonDiscordChatbot'ule> atSiteDjango> & C:/Users/Kaij/Documents/djangoTests/django_tailwind_project/env/Scripts/
from pythonDiscordChatbot.procechatSiteDjango/todoproject/todoapp/testChatFunctions.pyssLesson import *
ModuleNotFoundError: No module nametSiteDjango\todoproject\todoapp\testChatFunctions.py", line 6, in <module>d 'pythonDiscordChatbot
Here's what I have tried:
# Bring your packages onto the path
import sys, os
sys.path.append(os.path.abspath(os.path.join('..', 'pythonDiscordChatbot')))
# Now do your import
from pythonDiscordChatbot.processLesson import *
# from pythonDiscordChatbot.processLesson import routes
routes("hello", "website_180.02.1")

Python : Flask importing a file from current directory, but subcategory

I'm struggling to import a folder that has many engines I need to use. I'm importing from main_file.py.
So I think I can use - from engines import qr_code_gen, but I need to import a class which is named _QRCode_ so I tried using - from .engines.qr_code_gen import _QRCode_, but it says "module engines was not found".
Structure:
Server/start.sh
Server/wsgi.py
Server/application/main_file.py
Server/application/engines/qr_code_gen.py
Server/application/engines/__init__.py
...
I used sys.path in main_file.py and I got -
['C:\Users\Dzitc\Desktop\winteka2',
'C:\Users\Dzitc\AppData\Local\Programs\Python\Python37\Scripts\flask.exe',
'c:\users\dzitc\appdata\local\programs\python\python37\python37.zip',
'c:\users\dzitc\appdata\local\programs\python\python37\DLLs',
'c:\users\dzitc\appdata\local\programs\python\python37\lib',
'c:\users\dzitc\appdata\local\programs\python\python37',
'C:\Users\Dzitc\AppData\Roaming\Python\Python37\site-packages',
'c:\users\dzitc\appdata\local\programs\python\python37\lib\site-packages',
'c:\users\dzitc\appdata\local\programs\python\python37\lib\site-packages\win32',
'c:\users\dzitc\appdata\local\programs\python\python37\lib\site-packages\win32\lib',
'c:\users\dzitc\appdata\local\programs\python\python37\lib\site-packages\Pythonwin']
Going from comments you can import engine package.
Try this then:
import engines
engines.qr_code_gen._QRCode_

distutils wildcard entry for include_dir

I am setting up a package using distutils.
I need to allow access to a module that is built during the set-up process and is located in ./build/temp.linux-x86_64-3.6. I do this by including the
include_dirs=["./build/temp.linux-x86_64-3.6"]
when adding the extension to the distutils Configuration.
My question is there a way of setting this using a wildcard such as:
include_dirs=["./build/temp.linux*"]
as when I try this it fails, citing error:
Nonexistent include directory ‘build/temp.linux*’ [-Wmissing-include-dirs]
The reason I want this is that the build folder will be named differently depending on the system. Alternatively if anyone knows a way of figuring out what this temp build folder will be called that would also work.
The way I have got around this problem is as follows:
def return_major_minor_python():
import sys
return str(sys.version_info[0])+"."+str(sys.version_info[1])
def return_include_dir():
from distutils.util import get_platform
return get_platform()+'-'+return_major_minor_python()
Then when calling config.add_extension() using:
include_dirs=['build/temp.' + return_include_dir()]
So the whole process for adding a f90wrapped, f2py extension to a python package is:
def setup_fort_ext(args,parent_package='',top_path=''):
from numpy.distutils.misc_util import Configuration
from os.path import join
import sys
config = Configuration('',parent_package,top_path)
fort_src = [join('PackageName/','fortran_source.f90')]
config.add_library('_fortran_source', sources=fort_src,
extra_f90_compile_args = [ args["compile_args"]],
extra_link_args=[args["link_args"]])
sources = [join('PackageName','f90wrap_fortran_source.f90')]
config.add_extension(name='_fortran_source',
sources=sources,
extra_f90_compile_args = [ args["compile_args"]],
extra_link_args=[args["link_args"]],
libraries=['_tort'],
include_dirs=['build/temp.' + return_include_dir()])
return config
if __name__ == '__main__':
import sys
import subprocess
import os
install_numpy() #installs numpy
install_dependencies() #calls to pip to install any requirements
from numpy.distutils.core import setup
config = {'name':'PackageName',
'version':__version__,
'project_description':'Some Package description',
'description':'Some package Description',
'long_description': open('README.txt').read(),
'long_description_content_type':'text/markdown',
'author':'Your name here',
'author_email':'your email here',
'url':'link to git repo here',
'python_requires':'>=3.3',
'packages':['PackageName'],
'package_dir':{'PackageName':'PackageName'},
'package_data':{'PackageName':['*so*']},
'name': 'PackageName'
}
config_fort = setup_fort_ext(args,parent_package='PackageName',top_path='')
config2 = dict(config,**config_fort.todict())
setup(**config2)
where the source fortran_source.f90 is wrapped beforehand and the resulting wrapped source file (f90wrap_fortran_source.f90) is included as a library, and subsequently compiled by f2py.
args in the above is just a dict with the any linking or compile args you wish to pass through.

The managed object is not valid - Dynamo Crashes

The following error in Dynamo is bugging me since many hours.
Warning:
IronPythonEvaluator.EvaluateIronPythonScript operation failed.
Traceback (most recent call last):
File " < string > ", line 33, in < module>
Exception: The managed object is not valid.
I’m not sure why the error has occur would appreciate if someone share its solution with me. Thank you
import clr
clr.AddReference('ProtoGeometry')
import Autodesk.DesignScript.Geometry
# Import Element wrapper extension methods
clr.AddReference("RevitNodes")
import Revit
clr.ImportExtensions(Revit.Elements)
# Import geometry conversion extension methods
clr.ImportExtensions(Revit.GeometryConversion)
# Import DocumentManager and TransactionManager
clr.AddReference("RevitServices")
import RevitServices
from RevitServices.Persistence import DocumentManager
from RevitServices.Transactions import TransactionManager
doc = DocumentManager.Instance.CurrentDBDocument
uiapp = DocumentManager.Instance.CurrentUIApplication
app = uiapp.Application
# Import RevitAPI
clr.AddReference("RevitAPI")
from Autodesk.Revit.DB import *
import System
from System import Array
from System.Collections.Generic import *
import sys
pyt_path = r'C:\Program Files (x86)\IronPython 2.7\Lib'
sys.path.append(pyt_path)
The above are my standard imports while working with Dynamo/Revit API. It has been working for me for a while.
In all honesty I wish I had an "actual" answer why your script is not working. The only thing that is different than mine, is order in which you reference certain things. That should have no effect on their validity. It's Dynamo though, and it's very capricious.

Categories

Resources