How to save a file in usb directory [duplicate] - linux

I'm working with django 1.6.5 and python 2.7.
I have import feature in my app and I get error:
OSError: [Errno 18] Invalid cross-device link
I have problem with this part of code:
os.rename(db_temp, settings.DATABASES['bookmat']['NAME'])
code in settings:
'bookmat': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': '/my_projects/book/db/bookmat.sqlite3',
},

os.rename only works if source and destination are on the same file system. You should use shutil.move instead.

rename only works when the source and target names are on the same file system. You probably have different mounts. Otherwise you get that error. You can implement the same effect with a copy and a delete.

Related

Trying to set up a virtual environment with Python as directed from Learn Python the Hard Way

In the course Learn Python the Hard Way Exercise 46, you create a virtual environment by:
Installing vitualenv
making a directory for .venvs
creating a directory called lpthw then projects and a sub-dir called skeleton
adding a structure to the skeleton directory.
ex. lpthw - projects - skeleton - NAME, bin, setup.py, tests, and docs
Then you activate the virtual environment and install the nose module
Then you run nose tests.
When I run $nosetests from my virtual environment on powershell from the skeleton directory, I get the attribute error:
if isinstance(tests, collections.Callable) and not is_suite:
AttributeError: module 'collections' has no attribute 'Callable'
I have tried changing the references of collections.Callable to collections.abc.callable in the relevant file, when I do this, nose returns a result of 0 tests. There should be at least 1.
The setup file is as follows.
setup.py:
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
config = {
'description': 'My Project',
'author': 'William Smith',
'url': 'URL to go get it at.',
'download_url': 'Where to download it.',
'author_email': 'davwilsm1998#yahoo.com',
'version': '0.1',
'install_requires': ['nose'],
'packages': ['NAME'],
'scripts': [],
'name': 'projectname'
}
setup(**config)
I find my problems are two-fold:
1. My $nosetests is using the Lib folder from my main Python installation where it should be using the Virtual Environment's Lib folder.
2. My $nosetests is either returning an attribute error or it is not actually running the test in the proper directory if it all.
How do I either make this work, or uninstall this and try a different method to create a virtual environment?
I faced a similar problem when running nosetests.
I looked it up and as the error was in a file suite.py
I had to replace occurrences of collections.Callable to collections.abc.Callable inside the file.
The location of the file will be inside the .venvs folder.
.venvs/lpthw/lib/python3.10/site-packages/nose/suite.py
The tests ran after that.

Mac PyInstaller FileNotFoundError: [Errno 2] No such file or directory:

I try to build a standalone app with PyInstaller but I don't manage to do it when I add images to my app.
My .exe file works well when I don't include the .ico, .jpg, .png but when I inclue it, it doesn't work anymore (FileNotFoundError: [Errno 2] No such file or directory: 'Pictures/picture.png').
I tried to modify the --path option (I tried with the "main.py" path and also with "." path but it makes nothing.
My app uses Tkinter and Pillow for the images.
Interesting fact : I tried to run my .exe file with a copy of my picture files in user/username/pictures/ and it works. But I can't create a standalone app like that.
Mac version : 11.2.1
Python version : 3.8.5

ImportError: DLL load failed: The specified module could not be found -- IBM DB2

I know there have been many people with this same issue, but here is my situation which I have not been able to find the exact same problem. I am building an executable with pyinstaller and I keep getting the importError. I am using ibm_db package to connect to a IBM DB2 database and do inserts into a table using pandas to_sql method. I used pyinstaller on my program before I added the SQL code so I'm pretty sure it has something to do with my trying to connect to DB2, but for the life of me I cannot figure this out.
I get lots of warnings and info messages when I"m running pyinstaller but no errors that I see. I only get the error once I try to execute the executable file that pyinstaller built.
I have tried to run it in a virtual environment to try to isolate the issue but I am not that familiar with virtual environments, so I stop trying to use that.
Traceback (most recent call last):
File "rebate_gui_sql.py", line 9, in <module>
File "c:\users\dt24358\lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 627, in exec_module
exec(bytecode, module.__dict__)
File "site-packages\ibm_db.py", line 10, in <module>
File "site-packages\ibm_db.py", line 9, in __bootstrap__
File "imp.py", line 342, in load_dynamic
ImportError: DLL load failed: The specified module could not be found.
[11020] Failed to execute script rebate_gui_sql
Update: 5/1/2019 from comment below, here is my simple program
import pandas as pd
from tkinter import *
from tkinter import ttk
import ibm_db
import ibm_db_dbi as db
from sqlalchemy import create_engine
class Application(Frame):
def __init__(self, master):
ttk.Frame.__init__(self, master)
self.master = master
self.run_process()
def run_process(self):
engine = create_engine("db2+ibm_db://userid:password#url:port/database")
conn = engine.connect()
print("Connected to " + str(engine))
sql = '''
Select *
from rebteam.pd5
fetch first row only
'''
df = pd.read_sql(sql, conn)
print(df)
df.to_csv(r'c:\users\dt24358\scripts\pricing tool\GUI_SQL\test.csv', index=False)
self.result_label = Label(root, text="Select of PD5 Successful", bg="light green", width=80, justify=LEFT)
self.result_label.grid(row=0,columnspan=2)
root=Tk()
root.title("Rebate Bid Data Upload")
root.configure(background="light green")
app = Application(root)
root.mainloop()
This answer is relevant for these versions:
python - up to 3.7 (but not higher)
pyinstaller 3.4
setuptools 41.0.1
ibm_db 3.0.1
ibm_db_sa 0.3.4
sqlalchemy 1.3.3
There are separate issues here.
The immediate issue (the ImportError) is the failure to load ibm_db.dll
The ImportError happens because pyinstaller does not copy external (non python) libraries into the bundle unless you explicitly request that to happen.
pyinstaller will also not copy a Db2-client into the bundle unless you explicitly tell it to do that, which means that if your target hostname to which you deploy your built-executable does not already have a preconfigured preinstalled Db2-client then you will also experience the failure to load ibm_db module.
The pyinstaller option --add-binary gives a workaround for some kinds of ImportError , see example below. If you are not using SQLAlchemy just skip those parts of this answer.
The pyinstaller option --add-data gives a workaround for adding directories (for example the clidriver directory for adding a Db2-driver) when your target environment lacks a Db2-driver.
Note that this answer does not require you to use SQLAlchemy, the answer is also relevant if you are only using ibm_db (or ibm_db_dbi), in which case just skip the SQLAlchemy parts.
If your python script uses SQLAlchemy to access Db2, then you may see a second symptom at run time after building with pyinstaller. The run time symptom is either:
"sqlalchemy.exc.NoSuchModuleError: Can't load plugin:
sqlalchemy.dialects:ibm_db_sa"
or
"sqlalchemy.exc.NoSuchModuleError: Can't load plugin:
sqlalchemy.dialects:db2.ibm_db"
(depending on the prefix for the url given to create_engine())
This symptom sqlalchemy.exe.NoSuchModuleError is not specific to Db2 but can impact other databases when used via SQLAlchemy with an external dialect ( Db2, teradata, snowflake, presto,...). Databases that use SQLAlchemy internal dialects may just work out of the box.
Here is one workaround for SQLAlchemy, other workarounds are possible.
SQLAlchemy external dialects use pkg_resources entry_points to allow SQLAlchemy to exploit them, but pyinstaller cannot yet handle these, without some assistance from you. Such entry point information is a kind of meta data about the module.
This workaround uses pyinstaller hooks to collect the metadata of the relevant modules , and tells pyinstaller the directory (or directories) that contain these hook files. For Db2 with SQLAlchemy, three hook files are needed, hook-ibm_db.py, hook-ibm_db_sa.py, hook-sqlalchemy.py. I choose to put these hook files in the same directory as my source file python script.
The contents of each of these files is trivial two lines, and the contents differ only by the module name contained within. Here is an example of one of the files hook-sqlalchemy.py (for the other 2 required files, just replace the module name appropriately):
from PyInstaller.utils.hooks import copy_metadata
datas = copy_metadata('sqlalchemy')
To add ibm_db.dll via the --add-binary method, you can either use a command line option to pyinstaller or edit the spec file.
For handling load failures of ibm_db.dll alone, just use the --add-binary additional option like this:
pyinstaller -y --add-binary %LOCALAPPDATA%\Programs\Python\Python37\Lib\site-packages\ibm_db_dlls\ibm_db.dll;.\ibm_db_dlls your_script.py
If you want to include clidriver in your bundle, first find the fully qualified pathname to its location via:
pip show ibm_db
and in the output of that command see the Location: line which has the first part of the fully qualified pathname , so you append \CLIDRIVER to that path and use it in the --add-data additional option like this:
--add-data="c:\path\to\clidriver;.\clidriver"
If you do include clidriver in your bundle, there are additional considerations, see the notes section below.
For apps that also use SQLAlchemy, you need additional steps.
Suppose that the ibm_db.dll lives in this directory:
%LOCALAPPDATA%\programs\python\python37\lib\site-packages\ibm_db_dlls
and you make a variable in a CMD.EXE shell to point to that location:
> set ibm_db_path=%LOCALAPPDATA%\programs\python\python37\lib\site-packages\ibm_db_dlls
For an MS-Windows batch file (using ^ as line continuation character), the pyinstaller command line example to handle both of the workarounds mentioned above is:
pyinstaller -y ^
--additional-hooks-dir=. ^
--hidden-import ibm_db_sa.ibm_db ^
--hidden-import ibm_db_dbi ^
--hidden-import ibm_db ^
--add-binary %LOCALAPPDATA%\Programs\Python\Python37\Lib\site-packages\ibm_db_dlls\ibm_db.dll;.\ibm_db_dlls ^
your_script.py
Notes:
If your python script explicitly imports the SQLAlchemy modules then you do not
need to specify them via --hidden-import options (buy you still need
the hooks for SQLAlchemy to operate after bundling).
For ibm_db versions up to 3.0.2, the ibm_db.dll needs to be in subdirectory ibm_db_dlls in your
bundle, which is the reason for specifying that destination on the
--add-binary option.
If you are building for Linux/Unix, instead of ^. use \ as the line continuation character as usual.
If you intend to copy your built executable to a new hostname, and that new hostname does not already have a pre-installed Db2-client , and you do not wish to install a separate Db2-client on the target, then you can bundle clidriver with the pyinstaller output with the --add-data option shown above.
If you bundle clidriver be aware that you may also need to bundle its configuration files (such as db2dsdriver.cfg and db2cli.ini) if they are in non-default locations, depending on whether your code uses externally configured DSNs or long connection-strings. If you do not bundle such configuration files (implicitly or explicitly) and you deploy your built environment to a different hostname than the build environment then you will need to reconfigure those files at the target hostname. The default location for these files is in the clidriver\cfg directory which will get included via --add-data as mentioned earlier.
If you bundle clidriver, and if you are using encrypted connections to Db2 via TLS/SSL, be aware you may also need to bundle additional files such as certificates, keystore/stash files etc when you run the pyinstaller build.
If you bundle clidriver, be aware that IBM refreshes this component a couple of times per year with bug fixes and security fixes and new functions, so you may need to refresh your executables periodically to prevent them from becoming security holes by being frozen in time with old versions.
if you bundle clidriver and if you need to use odbcad32 on the target hostname for configuring Db2 DSNs, then following deployment on the target hostname remember to run the clidriver\bin\db2cli install -setup command on the target hostname.
Thanks for your question and answer. I had met the same situation in Windows7 Python3.7 ibm-db 3.0.1
with your hint,I think the reason is that exe can't find *.dll in clidriver\bin and ibm_db.dll,
and solve it with a similar method in two steps
Frist:
the same as you, add clidriver directory to system path
**\site-packages\clidriver\bin
Second
pack with argument --add-binary
Pyinstaller --add-binary **\Lib\site-packages\ibm_db_dlls\ibm_db.dll;.\ibm_db_dlls myproject.py
Then it's OK!
similar question:
PyQt5 Executable is crashing with Missing DLL

OS error: [WinError 123] seen when while un compressing a tarfile(created in linux)

I have a tarfile in which one folder is having name #997_Mon_Oct_14_17:12:29_CST_2013.tar.
This file is created in a linux environment. I want to untar this file in windows env.
Using tarfile, if i extract i am getting below error. Since windows dont't accept folder name with ":".
OS error: [WinError 123] The filename, directory name, or volume label syntax is incorrect: 'C:\Users\310190224\Desktop\test\.\lib\modules\#997_Mon_Oct_14_17:12:29_CST_2013'
Code snippet:
import tarfile
tar=tarfile.open("file name","r")
tar.extractall()
Can anyone help to override this problem.

importing a python function from a file in other directory which depends on another file

This is my directory structure
-directory1
|-currentlyWritingCode
-directory2
|-__init__.py
|-helper.py
|-view.ui
The helper.py is a UI from pyqt4 framework. It needs the view.ui file .
it has following code to load the ui data
viewBase, viewForm = uic.loadUiType("view.ui")
now in directory1 in the currently writing code I did this
import directory2.helper
when I run the code in currentlyWritingCode it is throwing an error that
FileNotFoundError: [Errno 2] No such file or directory: 'view.ui'
What to do now?
using python3.5 from anaconda on Centos 7
Use os.path.join(os.path.dirname(os.path.realpath(__file__)),'view.ui') in place of view.ui. This will ensure you correctly reference the folder that the python file lives in, regardless of the code that imports it.
Note: Make sure you have import os with your other imports.
How does this work?
__file__ is an attribute of the module you are importing. It contains the path to the module file. See this answer. However, this path is not necessarily an absolute path. os.path.realpath returns the absolute path (it even follows symlinks if there are any). At this point we have a full path to the module, so we take the path to the directory (os.path.dirname) and join it with the original filename (which we assumed to be relative to the original module and so should be in the aforementioned directory). os.path.join ensures that the correct \ or / is used when constructing a file path so that the code works on any platform.

Resources