GAE - Flask - OSError: [Errno 13] path not accessible: - python

I am trying since 2 days to get flask running, but with all templates i get the same error messages
I am using Windows 7 64bit
https://github.com/kamalgill/flask-appengine-template/
OOSError: [Errno 13] path not accessible: 'c:\python27\dlls'
from pkq_resources , function : find_on_path
So I thought maybe it's a windows thing so I deployed it to my GAE app and it worked.
http://kanta3d.appspot.com
But i don't want to deploy it every time, this would kill the workflow.
I googled this error but I could not find a fix.
I did some investigation and this function in pkq_resources throws the error
for entry in os.listdir(path_item): # this throws the error
.
def find_on_path(importer, path_item, only=False):
"""Yield distributions accessible on a sys.path directory"""
path_item = _normalize_cached(path_item)
if os.path.isdir(path_item) and os.access(path_item, os.R_OK):
if path_item.lower().endswith('.egg'):
# unpacked egg
yield Distribution.from_filename(
path_item, metadata=PathMetadata(
path_item, os.path.join(path_item,'EGG-INFO')
)
)
else:
# scan for .egg and .egg-info in directory
for entry in os.listdir(path_item):
lower = entry.lower()
if lower.endswith('.egg-info'):
fullpath = os.path.join(path_item, entry)
if os.path.isdir(fullpath):
# egg-info directory, allow getting metadata
metadata = PathMetadata(path_item, fullpath)
else:
metadata = FileMetadata(fullpath)
yield Distribution.from_location(
path_item,entry,metadata,precedence=DEVELOP_DIST
)
elif not only and lower.endswith('.egg'):
for dist in find_distributions(os.path.join(path_item, entry)):
yield dist
elif not only and lower.endswith('.egg-link'):
for line in open(os.path.join(path_item, entry)):
if not line.strip(): continue
for item in find_distributions(os.path.join(path_item,line.rstrip())):
yield item
break
full source at :
https://github.com/kamalgill/flask-appengine-template/blob/master/src/pkg_resources.py

I think taking ownership of the folder in question should work. I had the same issue on Windows 10 and I had to do this on powershell to overcome this problem.
.\takeown.exe /f "C:\users\" /r /d y

Related

Issue with NameError

So I am fairly new with coding in Python and in general and I am trying to write a program that will backup files in a giving folder. However, I continue to get a "NameError: name 'src' is not defined. I see some other questions similar about this error but none have yet to make me understand what I am doing wrong or why I get this error. As far as I understand it I am defining 'src' in the code below. Any help would be greatly appreciated.
ERROR:
File "/home/student/PycharmProjects/Lab1.py/Lab5.5.py", line 1, in processing
backup(src, dest)
NameError: name 'src' is not defined
def backup(src, dest):
#Checking if src and dest directories exist
sourceFilePath = input('Enter folder path to be backed up')
destFilePath = input('Please choose where you want to place the backup')
#found = true
for directory in [src, dest]:
if not isdir(directory):
print(f'could not find {directory}')
found = False
if not found:
exit(1)
#for each file in src
for sourceFileName in listdir(src):
#computing file paths
sourceFilePath = path.join(src, sourceFileName)
destFilePath = path.join(dest, sourceFileName)
#backing up file
copy2(sourceFilePath, destFilePath)
#entry point
if __name__=='__main__':
#validating length of command line arguments
if len(argv) != 3:
print(f'Usage: {argv[0]} SRC DEST')
exit(1)
#performing backup
backup(argv[1], argv[2])
#logging status message
print('Backup succesful!')
why are you prompting the user for src and dest path though you already pass them as command args? The issue probably came from the fact you didn't provide the src arg while running the script. Things like
python script.py srcpath dstpath

finding file with unicode characters using Path.glob in python3 on OSX

How do I find a filename starting with "dec2💜file" that has an extension on OSX?
In my case, I have only one .ppt file in the Documents directory. So, the result should be:
dec2💜file.ppt
Here is the code:
my_pathname='Documents'
my_filename='dec2💜file'
my_glob = "{c}.{ext}".format(c=my_filename, ext='*')
try:
my_filename = str(list(pathlib.Path(my_pathname).glob(my_glob))[0])
except Exception as ex:
print("Error - {d}/{f} - {e}".format(d=my_pathname, f=my_glob, e=str(ex)))
exit(1)
print("Found it - {f}".format(f=my_filename))
Current result:
ERROR - Documents/dec2💜file.* - list index out of range
How do I get it to find the file and print:
Found it - dec2💜file.ppt
After creating a folder called test, and a file inside it called dec2💜file.txt, I ran this:
import pathlib
my_pathname = 'test'
my_filename = 'dec2💜file'
my_glob = "{c}.{ext}".format(c=my_filename, ext='*')
try:
my_filename = str(list(pathlib.Path(my_pathname).glob(my_glob))[0])
except Exception as ex:
print("Error - {d}/{f} - {e}".format(d=my_pathname, f=my_glob, e=str(ex)))
exit(1)
print("Found it - {f}".format(f=my_filename))
And got:
Found it - test\dec2💜file.txt
So, I can only conclude there is no folder called Documents inside the working directory where your script runs. Try replacing my_pathname with a full path name, or ensure your script runs in the parent directory of Documents.
You can do this by either changing the working directory of the script from your IDE or on the command line, or by using os.chdir or something similar to change directory before the relevant part of the script.

subprocess.Popen fails in nginx

I am developing a simple website using Flask + gunicorn + nginx on a Raspberry Pi with Rasbian Jessie.
I am stuck at launching a process with this Python code:
def which(program):
def is_exe(fpath):
return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
fpath, fname = os.path.split(program)
if fpath:
if is_exe(program):
return program
else:
for path in os.environ["PATH"].split(os.pathsep):
path = path.strip('"')
exe_file = os.path.join(path, program)
if is_exe(exe_file):
return exe_file
return None
mplayer_path = which("mplayer")
try:
player = subprocess.Popen([mplayer_path, mp3], stdin=subprocess.PIPE)
except:
return render_template('no_mp3s.html', mp3_message=sys.exc_info())
"mp3" is the path to an mp3 file while "mplayer_path" is the absolute path to mplayer, as returned by the which function described in this answer.
The code works in development when I launch flask directly. In production, when I access the website through nginx, I get the following error message through the no_mp3s.html template:
type 'exceptions.AttributeError'
AttributeError("'NoneType' object has no attribute 'rfind'",)
traceback object at 0x7612ab98
I suspect a permission issue with nginx, but being very new with Linux I am a bit lost!
Edit:
I should add that nowhere in my code (which fits in a single file) I call rfind(). Also, I am sure that the error is caught in this specific try/except because it is the only one that outputs to no_mp3s.html.
Edit:
Following blubberdiblub comments I found out that it is the which function that does not work when the app is run in nginx. Hard coding the path to mplayer seems to work!

python import_module function not loading package

I have below openstack rally code which is dynamically loading python modules from given path using below function.
def load_plugins(dir_or_file):
if os.path.isdir(dir_or_file):
directory = dir_or_file
LOG.info(_("Loading plugins from directories %s/*") %
directory.rstrip("/"))
to_load = []
for root, dirs, files in os.walk(directory, followlinks=True):
to_load.extend((plugin[:-3], root)
for plugin in files if plugin.endswith(".py"))
for plugin, directory in to_load:
if directory not in sys.path:
sys.path.append(directory)
fullpath = os.path.join(directory, plugin)
try:
fp, pathname, descr = imp.find_module(plugin, [directory])
imp.load_module(plugin, fp, pathname, descr)
fp.close()
LOG.info(_("\t Loaded module with plugins: %s.py") % fullpath)
except Exception as e:
LOG.warning(
"\t Failed to load module with plugins %(path)s.py: %(e)s"
% {"path": fullpath, "e": e})
if logging.is_debug():
LOG.exception(e)
elif os.path.isfile(dir_or_file):
plugin_file = dir_or_file
LOG.info(_("Loading plugins from file %s") % plugin_file)
if plugin_file not in sys.path:
sys.path.append(plugin_file)
try:
plugin_name = os.path.splitext(plugin_file.split("/")[-1])[0]
imp.load_source(plugin_name, plugin_file)
LOG.info(_("\t Loaded module with plugins: %s.py") % plugin_name)
except Exception as e:
LOG.warning(_(
"\t Failed to load module with plugins %(path)s: %(e)s")
% {"path": plugin_file, "e": e})
if logging.is_debug():
LOG.exception(e)
This was working absolutely fine as till 2 days ago. Now I am not getting error but its not loading any classes as well.
I only the first log information is printed and its getting printed and the while looking for loaded classes it fails. from below ensure_plugins_are_loaded is internally calling above function.
File "<decorator-gen-3>", line 2, in _run
File "build/bdist.linux-x86_64/egg/rally/plugins/__init__.py", in ensure_plugins_are_loaded
File "build/bdist.linux-x86_64/egg/rally/task/engine.py", in validate
Update 1
I tried calling a simple importlib.import_module('/opt/plugins'). Still not error thrown from import_module but python still can't find loaded modules. I am trying to find modules using subs = cls.subclasses() which extends given subclass.
Update 2
I also tried to use the same code without creating bdist_egg package.
Just did
python setup.py develop
and it works fine. So i am not sure what is problem when using it with bdist_egg.

Error when using os.stat - Python

Solved: Adding an os.chdir(myArg) resolved the issue.
I'm getting an error when trying to run the following code on anything other than my home directory or files/direcs that I own.
FileNotFoundError: [Errno 2] No such file or directory:
I created a file in root and changed ownership on the file to pi:pi (user running the script). If I specify that file directly, it works, however if I run the script on "/", it will not read that or any other file/direc. I also created a directory /tempdir_delete/ and changed ownership to pi:pi.. If I run the script specifically on "/tempdir_delete/*", it works, but if I leave off the * it fails.
Why does it fail on all except /home/pi/ or files that I explicitly specify and own? It's running the stat as user pi, which is granted by sudo to perform the stat. Also, why do I have to specify the file that I own explicitly? Shouldn't it see that file in root and work because I own it?
import os
import re
import sys
import pwd
myReg = re.compile(r'^\.')
myUID = os.getuid()
myArg = sys.argv[1]
print(os.getuid())
print(pwd.getpwuid(int(myUID)))
print(myArg)
def getsize(direct):
if os.path.isfile(direct) == True:
statinfo = os.stat(myArg)
print(str(statinfo.st_size))
else:
for i in os.listdir(direct):
try:
statinfo = os.stat(i)
if myReg.search(i):
continue
else:
print(i + ' Size: ' + str(statinfo.st_size))
except:
print('Exception occurred, can't read.')
continue
getsize(myArg)
Solved. Adding an os.chdir(myArg) worked to resolve the issue.

Categories

Resources