nuitka fails to generate executable due to "The filename or extension is too long" - filenames

I've been trying to compile/generate a standalone executable (.exe) with nuitka but it fails every time with the message:
Nuitka:INFO:Total memory usage before running scons: 2.72 GB (2920177664 bytes):
scons: *** [main_executable.dist\main_executable.exe] The filename or extension is too long
I'm new to this programming but I think I've tried just about everything. I moved my *.py files to directory C:\main to shorten the path to no avail. I've rename the file to produce "main.exe" from "main_executable" to no avail.
My python is installed in here:
'C:\users\test\Anaconda3...'
I came across this function below to shorten the path but I have no idea how to implement it: (taken from http://code.activestate.com/recipes/286179-getshortpathname/)
Could you kindly help. Thanks.
def getShortPathName(filepath):
"Converts the given path into 8.3 (DOS) form equivalent."
import win32api, os
if filepath[-1] == "\\":
filepath = filepath[:-1]
tokens = os.path.normpath(filepath).split("\\")
if len(tokens) == 1:
return filepath
ShortPath = tokens[0]
for token in tokens[1:]:
PartPath = "\\".join([ShortPath, token])
Found = win32api.FindFiles(PartPath)
if Found == []:
raise WindowsError, 'The system cannot find the path specified: "%s"' % (PartPath)
else:
if Found[0][9] == "":
ShortToken = token
else:
ShortToken = Found[0][9]
ShortPath = ShortPath + "\\" + ShortToken
return ShortPath

Related

Dropbox - Automatic Refresh token Using oauth 2.0 with offlineaccess

I now: the automatic token refreshing is not a new topic.
This is the use case that generate my problem: let's say that we want extract data from Dropbox. Below you can find the code: for the first time works perfectly: in fact 1) the user goes to the generated link; 2) after allow the app coping and pasting the authorization code in the input box.
The problem arise when some hours after the user wants to do the same operation. How to avoid or by-pass the newly generation of authorization code and go straight to the operation?enter code here
As you can see in the code in a short period is possible reinject the auth code inside the code (commented in the code). But after 1 hour or more this is not loger possible.
Any help is welcome.
#!/usr/bin/env python3
import dropbox
from dropbox import DropboxOAuth2FlowNoRedirect
'''
Populate your app key in order to run this locally
'''
APP_KEY = ""
auth_flow = DropboxOAuth2FlowNoRedirect(APP_KEY, use_pkce=True, token_access_type='offline')
target='/DVR/DVR/'
authorize_url = auth_flow.start()
print("1. Go to: " + authorize_url)
print("2. Click \"Allow\" (you might have to log in first).")
print("3. Copy the authorization code.")
auth_code = input("Enter the authorization code here: ").strip()
#auth_code="3NIcPps_UxAAAAAAAAAEin1sp5jUjrErQ6787_RUbJU"
try:
oauth_result = auth_flow.finish(auth_code)
except Exception as e:
print('Error: %s' % (e,))
exit(1)
with dropbox.Dropbox(oauth2_refresh_token=oauth_result.refresh_token, app_key=APP_KEY) as dbx:
dbx.users_get_current_account()
print("Successfully set up client!")
for entry in dbx.files_list_folder(target).entries:
print(entry.name)
def dropbox_list_files(path):
try:
files = dbx.files_list_folder(path).entries
files_list = []
for file in files:
if isinstance(file, dropbox.files.FileMetadata):
metadata = {
'name': file.name,
'path_display': file.path_display,
'client_modified': file.client_modified,
'server_modified': file.server_modified
}
files_list.append(metadata)
df = pd.DataFrame.from_records(files_list)
return df.sort_values(by='server_modified', ascending=False)
except Exception as e:
print('Error getting list of files from Dropbox: ' + str(e))
#function to get the list of files in a folder
def create_links(target, csvfile):
filesList = []
print("creating links for folder " + target)
files = dbx.files_list_folder('/'+target)
filesList.extend(files.entries)
print(len(files.entries))
while(files.has_more == True) :
files = dbx.files_list_folder_continue(files.cursor)
filesList.extend(files.entries)
print(len(files.entries))
for file in filesList :
if (isinstance(file, dropbox.files.FileMetadata)) :
filename = file.name + ',' + file.path_display + ',' + str(file.size) + ','
link_data = dbx.sharing_create_shared_link(file.path_lower)
filename += link_data.url + '\n'
csvfile.write(filename)
print(file.name)
else :
create_links(target+'/'+file.name, csvfile)
#create links for all files in the folder belgeler
create_links(target, open('links.csv', 'w', encoding='utf-8'))
listing = dbx.files_list_folder(target)
#todo: add implementation for files_list_folder_continue
for entry in listing.entries:
if entry.name.endswith(".pdf"):
# note: this simple implementation only works for files in the root of the folder
res = dbx.sharing_get_shared_links(
target + entry.name)
#f.write(res.content)
print('\r', res)

xhtml2pdf in django - issue link_callback

I am trying to generate a pdf from an html-template in django. Therefore i use pretty much the basic methods found in the web. The issue is that in can get it to generate the content of my template, but not the images from my media directory. I always get the following error:
SuspiciousFileOperation at /manager/createpdf/
The joined path is located outside of the base path component
Since i can get some result, i assume that nothing is wrong with my view. Here is my render_to_pdf
def render_to_pdf(template_src, context_dict):
template = get_template(template_src)
html = template.render(context_dict)
result = BytesIO()
pdf = pisa.pisaDocument(BytesIO(html.encode('UTF-8')), result, link_callback=link_callback)
if not pdf.err:
return HttpResponse(result.getvalue(), content_type='application/pdf')
return None
and the link_callback:
def link_callback(uri, rel):
result = finders.find(uri)
if result:
if not isinstance(result, (list, tuple)):
result = [result]
result = list(os.path.realpath(path) for path in result)
path=result[0]
else:
sUrl = settings.STATIC_URL
sRoot = settings.STATIC_ROOT
mUrl = settings.MEDIA_URL
mRoot = settings.MEDIA_ROOT
if uri.startswith(mUrl):
path = os.path.join(mRoot, uri.replace(mUrl, ""))
elif uri.startswith(sUrl):
path = os.path.join(sRoot, uri.replace(sUrl, ""))
else:
return uri
# make sure that file exists
if not os.path.isfile(path):
raise Exception( 'media URI must start with %s or %s' % (sUrl, mUrl))
return path
I am pretty much sure that the link_callback doesnt do it's purpose. But my knowledge is to little to patch it. I also assume that i configured the media directory correctly. I can access the media files in other views/templates.
Help is very appreciated, since i spend quiet some hours on this issue... A big thx to all the are going to contribute here!
OK, i found it! In the finders.py i checked the find-method. It turns out that the find method only looks for files in the static directory and disregards the media directory. i just deleted all the lins and it works now. Here is the code:
def link_callback(uri, rel):
sUrl = settings.STATIC_URL
sRoot = settings.STATIC_ROOT
mUrl = settings.MEDIA_URL
mRoot = settings.MEDIA_ROOT
if uri.startswith(mUrl):
path = os.path.join(mRoot, uri.replace(mUrl, ""))
elif uri.startswith(sUrl):
path = os.path.join(sRoot, uri.replace(sUrl, ""))
else:
return uri
if not os.path.isfile(path):
raise Exception( 'media URI must start with %s or %s' % (sUrl, mUrl))
return path

f.open() issue resulting in Unbound error for f.close()

I don't quite have an answer but I'm narrowing it down. Somehow I'm mixing/confusing types, I believe, between what is provided by commands like 'os.path' and type str().
As I've made the assignment of the logfile(s) globally, even though I can print it in the function, when the variable is used in fout = open(... it's actually a null that's being referenced, i.e. open() doesn't like/can't use the type it finds.
The error:
UnboundLocalError: local variable 'fout' referenced before assignment
I am simply writing a log of dot files (left on USB drives by OSX) for deletion, but the try/except is now falling over. First the original version.
working code:
logFile = "/Users/dee/Desktop/dotFile_names.txt"
try:
fout = open(logFile, 'w')
for line in dotFile_names:
fout.write(line)
except IOError as e:
print ("Error : %s not found." % fout)
finally:
fout.close()
Attempting better practice, I sought to put the log file specs and path as variables so they can be modified if need be - I hope to make it cross platform workable. these variables are at the head of the program, i.e. not in main(), but I pass them in and print() statements have shown me they are successfully being referenced. i.e. I get this printed:
/Users/dee/Desktop/dotFile_names.txt
Despite this the error I get is:
UnboundLocalError: local variable 'fout' referenced before assignment -
error points at the "fout.close()" line
Error producing code
logFilespec = "dotFile_names.txt"
fullLogFileSpec = []
userDesktop = os.path.join(os.path.expanduser('~'), 'Desktop')
fullLogFilespec = os.path.join(userDesktop, logFilespec)
try:
print "opening " + fullLogFilespec
fout = open(fullLogFileSpec, 'w')
for line in dotFile_names:
print "..", # are we executing this line..?
fout.write(line)
except IOError as e:
print ("Error : %s not found." % fout)
finally:
print "\nclosing " + fullLogFilespec
fout.close()
I've found that if I modify this line by converting to a string
fout = open(fullLogFileSpec, 'w')
fout = open(str(fullLogFileSpec), 'w')
the error goes away, BUT NO file is created on the Desktop!
At the very least I guess that I am passing something unrecognisable to fout = open() but it is not being caught by the except. Then when I pass something that does seem to allow fout =open() to work it seems to be a ghost?
So I figure I am lost between a String and whatever kind of reference/pointer os.path.expanduser() gives me.
I'm sure it's insanely simple. Before adding the str() code I also checked all indentation, removing them all and adding back using the editor indent hotkeys, just in case that was affecting things somehow.
OK, it looks like I was wearing my dumb glasses, I think declaring
fullLogFileSpec = []
as a list instead of a string was my error.
Similar as it is, having re-written it without that list declaration this code is working fine:
logfile_directory = os.path.join(os.path.expanduser('~'),'Desktop')
log_bf_file_spec = 'ItemsFoundByFolder_' + Deez_1.current_datetime() + '.txt'
log_by_folder = os.path.join(logfile_directory, log_bf_file_spec)
the function later calls, with no error:
fout_by_folder = open(log_by_folder, 'w')

ASSERT failure in QList<T>::at: "index out of range" in Qt 5

I want to generate *.png files from my directory randomly in qt using qrand() function.
to do that I have created a QStringList object so that I can store all files I have in my
directory.thinking that I have some list of files in my QStringList object when I run my application it crush.
I have also warning in my issue pane:> warning: unknown escape sequence: '\D' [enabled by default]
applicationPath = "C:\\Users\\Tekme\Documents\\QtProject\\4Toddler";
^
the reason I add the above warning issues is that, I am on window machine so I am thinking the problem can be path problem
the code is
QString MainWindow::randomIcon()
{
QStringList iconFileList;
QString searchPath = applicationPath + "\\icons";//applicationPath =
QDir directory = QDir(searchPath);
QStringList filters;
filters << "*.png";
directory.setNameFilters(filters);
iconFileList = directory.entryList(QDir::AllEntries);//i have 6 *.png files
int randomIndex = qrand() % iconFileList.count();
return iconFileList.at(randomIndex);//my application crash here
}
Even when I try to replace iconFileList.at(randomIndex) by iconFileList.at(2) it crush.
I am sure I have more than 2 files in my directory
The answer is in the error:
applicationPath = "C:\\Users\\Tekme\Documents\\QtProject\\4Toddler";
Should be
applicationPath = "C:\\Users\\Tekme\\Documents\\QtProject\\4Toddler";
You are missing an extra slash

compressing the file using SevenZipSharp.dll

I want to compress and move the file using vb.net and SevenZipSharp.dll
c:\Backup\FULLBackup.bak -> c:\Archive\20130322.7z
I added a reference SevenZipSharp.dll
Imports SevenZip
SevenZip.SevenZipCompressor.SetLibraryPath(System.AppDomain.CurrentDomain.BaseDirectory & "\SevenZipSharp.dll")
Dim theCompressor As New SevenZipCompressor()
With theCompressor
.ArchiveFormat = OutArchiveFormat.SevenZip
.CompressionMode = CompressionMode.Create
.CompressionMethod = CompressionMethod.Default
.DirectoryStructure = False
.CompressionLevel = CompressionLevel.Normal
End With
theCompressor.CompressFilesEncrypted("c:\Archive\20130322.7z","c:\Backup\FULLBackup.bak")
I get an error : Can not load 7-zip library or internal COM error! Message: library is invalid.
I think it's simply the fact that the LibraryPath must not point to "SevenZipSharp.dll" but to "7z.dll".
http://blog.jongallant.com/2011/10/7-zip-dll-file-does-not-exist.html#.UaOLk0DxobA