How to close several folders in window 7 using Python - python-2.7

I seeking a way to close 20 open sub directories in window 7 using this python code. i want to close only those sub directories and not other open directories:
import os,sys,re
day = '2.1'
rootdir = r'G:\desktop'
for rootdir, dirs, files in os.walk(rootdir):
for subdir in dirs:
dayFolder = os.path.join(rootdir, subdir)
match = re.search('2022.January$',dayFolder)
if match:
os.close(os.path.join(dayFolder,day))
after i run it i get an error:
Traceback (most recent call last):
File "G:\desktop\y\general\test1.py", line 21, in <module>
os.close(os.path.join(dayFolder,day)) # close folder path
TypeError: an integer is required
>>>
update:
"close the sub directories" - i mean like clicking on the close button

Related

cx_Freeze: 'The system cannot find the file specified' error during build [win10] [PyQt4] [python2.7]

I'm trying to create a .exe file from a python script (which use PyQt4 GUI and matplotlib). I'm using cx_Freeze version 5.1.1 for 64-bit windows with the following setup.py:
import cx_Freeze
import sys
import matplotlib
base = "Win32GUI"
includes = ["atexit"]
buildOptions = dict(
#create_shared_zip=False,
#append_script_to_exe=True,
includes=includes
)
executables = [cx_Freeze.Executable(script = "main.py", base = base)] # icon = "chart32.jpg")]
cx_Freeze.setup(
name= "1ChPlotGUI",
options = dict(build_exe=buildOptions), # {"build_exe": {"packages": ["matplotlib"], "include_files":["chart32.jpg"]}},
version = "0.01",
description = "1 Channel Plotting app with GUI",
executables = executables
)
after running
python setup.py build
in the cmd from the position of
C:\Users\Us.Er\Pyth-examples\Qt\UI-examples\ChannelplotGUI-to-exe
I have something like this:
running build
running build_exe
copying c:\users\Us.Er\appdata\local\enthought\canopy\user\lib\site-
packages\cx_Freeze\bases\Win32GUI.exe -> build\exe.win-amd64-2.7\main.exe
copying
c:\users\Us.Er\appdata\local\enthought\canopy\user\scripts\python27.dll ->
build\exe.win-amd64-2.7\python27.dll
Traceback (most recent call last):
File "setup.py", line 23, in <module>
executables = executables
File "c:\users\Us.Er\appdata\local\enthought\canopy\user\lib\site-packages\cx_Freeze\dist.py", line 349, in setup
distutils.core.setup(**attrs)
File "C:\Users\Us.Er\AppData\Local\Enthought\Canopy\App\appdata\canopy-1.7.4.3348.win-x86_64\lib\distutils\core.py", line 151, in setup
dist.run_commands()
File "C:\Users\Us.Er\AppData\Local\Enthought\Canopy\App\appdata\canopy-1.7.4.3348.win-x86_64\lib\distutils\dist.py", line 953, in run_commands
self.run_command(cmd)
File "C:\Users\Us.Er\AppData\Local\Enthought\Canopy\App\appdata\canopy-1.7.4.3348.win-x86_64\lib\distutils\dist.py", line 972, in run_command
cmd_obj.run()
File "C:\Users\Us.Er\AppData\Local\Enthought\Canopy\App\appdata\canopy-1.7.4.3348.win-x86_64\lib\distutils\command\build.py", line 127, in run
self.run_command(cmd_name)
File "C:\Users\Us.Er\AppData\Local\Enthought\Canopy\App\appdata\canopy-1.7.4.3348.win-x86_64\lib\distutils\cmd.py", line 326, in run_command
self.distribution.run_command(command)
File "C:\Users\Us.Er\AppData\Local\Enthought\Canopy\App\appdata\canopy-1.7.4.3348.win-x86_64\lib\distutils\dist.py", line 972, in run_command
cmd_obj.run()
File "c:\users\Us.Er\appdata\local\enthought\canopy\user\lib\site-packages\cx_Freeze\dist.py", line 219, in run
freezer.Freeze()
File "c:\users\Us.Er\appdata\local\enthought\canopy\user\lib\site-packages\cx_Freeze\freezer.py", line 626, in Freeze
self._FreezeExecutable(executable)
File "c:\users\Us.Er\appdata\local\enthought\canopy\user\lib\site-packages\cx_Freeze\freezer.py", line 232, in _FreezeExecutable
self._AddVersionResource(exe)
File "c:\users\Us.Er\appdata\local\enthought\canopy\user\lib\site-packages\cx_Freeze\freezer.py", line 172, in _AddVersionResource
stamp(fileName, versionInfo)
File "c:\users\Us.Er\appdata\local\enthought\canopy\user\lib\site-packages\win32\lib\win32verstamp.py", line 159, in stamp
h = BeginUpdateResource(pathname, 0)
pywintypes.error: (2, 'BeginUpdateResource', 'The system cannot find the file specified.')
What is the possible solution for above problem?
EDIT
To be clear: I don't want to add any icon for now. I am happy with just a simple, working .exe
I have added the target in this way:
executables = [cx_Freeze.Executable(script = "main.py", base = base, targetName="main.exe")]
I have tried to add
targetDir = "C:\Users\Us.Er\Pyth-examples\Qt\UI-examples\ChannelplotGUI-to-exe"
anyway, the return is:
TypeError: __init__() got an unexpected keyword argument 'targetDir'
The main problem is as before - the error with last lines as:
h = BeginUpdateResource(pathname, 0)
pywintypes.error: (2, 'BeginUpdateResource', 'The system cannot find the file specified.')
In my case the issue was solved by changing
'build_exe': 'build_folder'
to
'build_exe': './/build_folder'
This is because open(pathname) would work on the pathname='build_folder\\executable.exe', allowing the code to advance during the check at the begginning of the stamp method, but BeginUpdateResource(pathname, 0) would only work on './/build_folder\\executable.exe'
Solution
options = {
'build_exe': {
'build_exe': './/build'
}
}
Note: .//build here, build is the folder name where you want to build your project.
Thanks to help of user jpeg I managed to successfully freeze the script.
To eliminate the problem with path I have added a line print(pathname) in win32verstamp.py before line 159.
The print statement worked fine showing the relative path to the newly made .exe file.
Despite showing the correct path, the error was still present. I went to the stamp() definition in win32verstamp.py and found a try - except block, and have inserted print(pathname) over there.
The part is:
def stamp(pathname, options):
# For some reason, the API functions report success if the file is open
# but doesnt work! Try and open the file for writing, just to see if it is
# likely the stamp will work!
#print("Current path is " + pathname)
try:
f = open(pathname, "a+b")
f.close()
print("Possible to open" + pathname) #<---line added
except IOError, why:
print "WARNING: File %s could not be opened - %s" % (pathname, why)r code here
....
Since that the freeze was possible. (Not sure why tho, I'm happy to add some info if explanation is known)
I had the same issue tying to freeze my PyQt5 app (using python 3.7 under windows 10) with the following message :
h = BeginUpdateResource(pathname, 0)
pywintypes.error: (2, 'BeginUpdateResource', 'Le fichier spécifié est introuvable.')
So I choose to use cx_freeze Sample provided as a first step.
(This samples are availables after cx_freeze installation under MyVENVpath\Lib\site-packages\cx_Freeze\samples)
The very basic PyQt5 exemple was working, but my case was way more complex as I used several sub Python class I have developed.
I honestly don't really understand why but I was able to make it work So here is all modifications I have performed :
In setup.py identify sub python files
add my personnal packages and class like this :
include = ["PyQt5", "PySerial", "myclass1", "myclass2", "myclass3", "PandasModel"]
packages = ["PySerial", "myclass1", "myclass2", "myclass3", "PandasModel", "pandas","math"]
Use relative path in setup.py
executables = [cx_Freeze.Executable(os.getcwd() + r'\..\..\MyFileName.py', base=base)]
include_files = [(os.getcwd() + r'\..\..\CalibrationTool.ui', r'Inputs\GUI\CalibrationTool.ui')
The reason for "...." is to jump two directories higher level, as my python.exe is in sub folders VENV\Script\
Add python Files containing "Myclass1" at same level as setup.py.
Even if in my application, class files are in a subfolder Input\Packages\Myclass1File.py, I had to copy-paste it at the same level as setup.py. This way the include and package line of setup.py work and was able to generate the executable.
Last but not least,the terminal command
I have no idea why but the only command who did suceed was:
to use full path to the python.exe and full path to the setup.py with the "build" at the end.
cmd:>C:\Folder1\Folder2\MyVENV\Scripts\python.exe D:\Folder1\Folder2\setup.py build
This finaly created the executable in a build folder under C:\Folder1\Folder2\MyVENV\Scripts\

Path error with Tesseract

I thought I'd got Tesseract to work on my Win 7 machine:
from PIL import Image
import pytesseract
pytesseract.pytesseract.tesseract_cmd = 'C:\\Program Files (x86)\\Tesseract-OCR\\tesseract.exe'
tessdata_dir_config = '--tessdata-dir "C:\\Program Files (x86)\\Tesseract-OCR\\tessdata"'
myFile = r"D:\temp\OCR\rightness_of_rendering.tif"
print(pytesseract.image_to_string(Image.open(myFile)))
tesseract.exe is located in C:\Program Files (x86)\Tesseract-OCR\tesseract.exe
eng.traineddata is located in C:\Program Files (x86)\Tesseract-OCR\tessdata
The error I get is
D:\LearnPython>D:\LearnPython\ocr_test.py
Traceback (most recent call last):
File "D:\LearnPython\ocr_test.py", line 14, in <module>
print(pytesseract.image_to_string(Image.open(myFile)))
File "C:\Python27\lib\site-packages\pytesseract\pytesseract.py", line 125, in
image_to_string
raise TesseractError(status, errors)
pytesseract.pytesseract.TesseractError: (1, u'Error opening data file \\Program
Files (x86)\\Tesseract-OCR\\eng.traineddata')
D:\LearnPython>
Which is one directory up, so I'm a little confused as how to set that up so it'll work properly.
From pytesseract github page
tessdata_dir_config = '--tessdata-dir "<replace_with_your_tessdata_dir_path>"'
# Example config: '--tessdata-dir "C:\\Program Files (x86)\\Tesseract-OCR\\tessdata"'
# It's important to add double quotes around the dir path.
pytesseract.image_to_string(image, lang='chi_sim', config=tessdata_dir_config)
Note that you need to provide config=tessdata_dir_config into your image_to_string call
So if you're using eng data it would be
print(pytesseract.image_to_string(Image.open(myFile), lang='eng', config=tessdata_dir_config))

I don't understand how this "os.join" function is working? I am getting errors constantly and no reading on os functions is helping me

Here's the code
sys.path.append( "../tools/" )
from parse_out_email_text import parseOutText #(its just another .py file that has a function I wrote)
from_sara = open("from_sara.txt", "r")
from_chris = open("from_chris.txt", "r")
from_data = []
word_data = []
temp_counter = 0
for name, from_person in [("sara", from_sara), ("chris", from_chris)]:
for path in from_person:
### only look at first 200 emails when developing
### once everything is working, remove this line to run over full dataset
temp_counter += 1
if temp_counter < 200:
path = os.path.join('..', path[:-1]) #(THIS IS THE PART I CAN'T GET MY HEAD AROUND)
print path
email = open(path, "r")
email.close()
print "emails processed"
from_sara.close()
from_chris.close()
When I run this, it gives me an error as shown below:
Traceback (most recent call last):
..\maildir/bailey-s/deleted_items/101.
File "C:/Users/AmitSingh/Desktop/Data/Udacity/Naya_attempt/vectorize_text.py", line 47, in <module>
email = open(path, "r")
IOError: [Errno 2] No such file or directory: '..\\maildir/bailey-s/deleted_items/101.'
I don't even have this """'..\maildir/bailey-s/deleted_items/101.'""" directory path on my laptop, I tried to change the path by replacing the '..' in the code by the actual path name to the folder where I keep all the files, and nothing changes.
path = os.path.join('..', path[:-1])
This code is part of an online course on machine learning and I have been stuck at this point for 3 hours now. Any help would be really appreciated.
(P.S. This is not a homework question and there are no grades attached to this, its a free online course)
your test data is not there so it cannot find it. you should run start-up code again and make sure the necessary maildir are all there.
Go to tools inside your udacity project directory and run startup.py.
It is about 400 Mb so sit back and relax!
I know this is extremely late, but I found this post after having the exact same problem.
All the answers that I found here and on other sites, even the issue requests in the original github, were just "run startup.py" I already did that. However, it was telling me:
Traceback (most recent call last):
File "K:\documents\Udacity\Mini-Projects\ud120-projects\text_learning\vectorize_text.py", line 48, in <module>
email = open(path, "r")
FileNotFoundError: [Errno 2] No such file or directory: '..\\maildir/bailey-s/deleted_items/101.'
Just like yours. I then found where this file was located and it was indeed on my computer
I added 'tools' to the os.path.join() line as you can see here:
for name, from_person in [("sara", from_sara), ("chris", from_chris)]:
for path in from_person:
### only look at first 200 emails when developing
### once everything is working, remove this line to run over full dataset
temp_counter += 1
if temp_counter < 200:
#path = os.path.join('..', path[:-1]) <---original
path = os.path.join('..','tools', path[:-1])
print(path)
email = open(path, "r")
This worked for me finally. So, I hope it helps anyone else that stumbles on this problem in the future.
Also, I noticed on some examples I found of other repos of the lessons. Their 'tools' folder was named 'utils'.
Here is an example, this is a repo that someone tweaked to use jupyter notebooks to run the lessons So, use the one that you have.
In your Udacity course folder, first go to tools directory, check if you have maildir folder present and if it has got subfolders in it, if they are present then go back to text_learning/vectorize_text.py, find this line of code path = os.path.join('..', path[:-1]), change it to path = os.path.join('../tools/', path[:-1]),
On terminal, cd text_learning , then python vectorize_text.py, this should solve the issue.
If this does not solve the issue, then Go to tools inside your udacity project directory and run startup.py. Wait till the process is complete
Repeat step 1.

Creating a small python program with cx_Freeze and pyGTK

I'm writing a small test-program that using python 2.7 and pygtk.
I will use Glade too
I need freeze this with cx_freeze.
This is my little program:
import gtk
win = gtk.Window()
win.connect("delete-event", gtk.main_quit)
win.show_all()
gtk.main()
And this is my setup:
from cx_Freeze import setup, Executable
import os, site, sys
## Get the site-package folder, not everybody will install
## Python into C:\PythonXX
site_dir = site.getsitepackages()[1]
include_dll_path = os.path.join(site_dir, "gnome")
## Collect the list of missing dll when cx_freeze builds the app
missing_dll = ['libgtk-win32-2.0-0.dll',
'libgdk-win32-2.0-0.dll',
'libatk-1.0-0.dll',
'libcairo-gobject-2.dll',
'libgdk_pixbuf-2.0-0.dll',
'libjpeg-8.dll',
'libpango-1.0-0.dll',
'libpangocairo-1.0-0.dll',
'libpangoft2-1.0-0.dll',
'libpangowin32-1.0-0.dll'
# 'libgnutls-26.dll',
# 'libgcrypt-11.dll',
# 'libp11-kit-0.dll'
]
## We also need to add the glade folder, cx_freeze will walk
## into it and copy all the necessary files
glade_path = os.path.join(site_dir, "gtk-2.0\\runtime\include\libglade-2.0\\")
glade_folder = 'glade'
# glade_folder = os.path.join(site_dir, "gtk-2.0\\")
# glade_folder += "runtime\include\libglade-2.0\glade"
## We need to add all the libraries too (for themes, etc..)
gtk_libs = ['etc', 'lib', 'share']
## Create the list of includes as cx_freeze likes
include_files = []
for dll in missing_dll:
include_files.append((os.path.join(include_dll_path, dll), dll))
## Let's add glade folder and files
include_files.append((glade_path, glade_folder))
## Let's add gtk libraries folders and files
for lib in gtk_libs:
include_files.append((os.path.join(include_dll_path, lib), lib))
base = None
## Lets not open the console while running the app
if sys.platform == "win32":
base = "Win32GUI"
executables = [
Executable("hello.py",
base=base
)
]
buildOptions = dict(
compressed=False,
includes=["gi"],
packages=["gi"],
include_files=include_files
)
setup(
name="test_gtk3_app",
author="my name",
version="1.0",
description="GTK 3 test",
options=dict(build_exe=buildOptions),
executables=executables
)
I run this command:
python setup_fr.py build
So, a folder called "build" is created with various files and directories. But, when I run the program "hello.exe", this error occurs:
Traceback (most recent call last): File "C:\Python27\lib\site-packages\cx_freeze-4.3.3-py2.7-win32.egg\cx_Freeze\initscripts\Console.py", line 27, in <module>
exec(code, m.__dict__) File "hello.py", line 1, in <module> File "C:\Python27\lib\site-packages\gtk-2.0\gtk\__init__.py", line 30, in <module>
import gobject as _gobject File "C:\Python27\lib\site-packages\gobject\__init__.py", line 26, in <module>
from glib import spawn_async, idle_add, timeout_add, timeout_add_seconds, \ File "C:\Python27\lib\site-packages\glib\__init__.py", line 22, in <module>
from glib._glib import * File "ExtensionLoader_glib__glib.py", line 22, in <module> File "ExtensionLoader_glib__glib.py", line 14, in __bootstrap__ ImportError: DLL load failed: Could not find the specified module.
I've looked at the "Build" folder to see if missing something related to gobject and found the "gobject._gobject.pyd" "libcairo-gobject-2.dll" and "GObject-2.0.typelib" files. I do not know exactly which file is still missing.
Can anyone help me figure out what is wrong?
Go to the gnome dir, which by itself is in the site-packages dir and manually copy all the .dll files (not the nested one) from this dir to your build/your-application-dir/ dir.
And it will work.

Bundling GTK3+ with cx_freeze

Platform is Windows 7 64bit using python 2.7 and GTK3 installed from
http://games.2g2s.de/?page_id=223 and PyGobject from here
http://sourceforge.net/projects/pygobjectwin32/files/?source=navbar
I used the script provided on wiki:
from cx_Freeze import setup, Executable
import os, site, sys
## Get the site-package folder, not everybody will install
## Python into C:\PythonXX
site_dir = site.getsitepackages()[1]
include_dll_path = os.path.join(site_dir, "gtk")
## Collect the list of missing dll when cx_freeze builds the app
missing_dll = ['libgtk-3-0.dll',
'libgdk-3-0.dll',
'libatk-1.0-0.dll',
'libcairo-2.dll',
'libcairo-gobject-2.dll',
'libgdk_pixbuf-2.0-0.dll',
'libpango-1.0-0.dll',
'libpangocairo-1.0-0.dll',
'libpangoft2-1.0-0.dll',
'libpangowin32-1.0-0.dll',
'libffi-6.dll',
'libfontconfig-1.dll',
'libfreetype-6.dll',
'libgio-2.0-0.dll',
'libglib-2.0-0.dll',
'libgmodule-2.0-0.dll',
'libgobject-2.0-0.dll',
'libpng15-15.dll',
]
## We also need to add the glade folder, cx_freeze will walk
## into it and copy all the necessary files
glade_folder = 'glade'
## We need to add all the libraries too (for themes, etc..)
gtk_libs = ['etc', 'lib', 'share']
## Create the list of includes as cx_freeze likes
include_files = []
for dll in missing_dll:
include_files.append((os.path.join(include_dll_path, dll), dll))
## Let's add glade folder and files
include_files.append((glade_folder, glade_folder))
## Let's add gtk libraries folders and files
for lib in gtk_libs:
include_files.append((os.path.join(include_dll_path, lib), lib))
base = None
## Lets not open the console while running the app
if sys.platform == "win32":
base = "Win32GUI"
executables = [
Executable("materii.py",
base=base
)
]
buildOptions = dict(
compressed = False,
includes = ["gi"],
packages = ["gi"],
include_files = include_files
)
setup(
name = "test_gtk3_app",
author = "Gian Mario Tagliaretti",
version = "1.0",
description = "GTK 3 test",
options = dict(build_exe = buildOptions),
executables = executables
)
The exe is compiled but fails to run, due to this
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\cx_Freeze\initscripts\Console.py", in <module>
exec code in m.__dict__
File "materii.py", line 2, in <module>
File "C:\Python27\lib\site-packages\gi\__init__.py", line 27, in <module>
from ._gi import _API
File "ExtensionLoader_gi__gi.py", line 22, in <module>
File "ExtensionLoader_gi__gi.py", line 14, in __bootstrap__
ImportError: DLL load failed: The specified module could not be found.
Line 2 from materii.py is
from gi.repository import Gtk
Can you help me please?
Go to the gnome dir, which by itself is in the site-packages dir and manually copy all the .dll files (not the nested one) from this dir to your build/your-application-dir/ dir. And it will work.