Wxpython drag and drop folder path, Popen not working with spaces on Windows - drag-and-drop

I have the below code which allows the user to drag and drop a folder to get the folder path. I then take this folder path and use it to pass through to a command line application in Windows using Popen. This all works fine except if there are spaces in the folder path, which then fails. I am currently getting round this by using win32api.GetShortPathName(folder_list) which shortens them to DOS 8.3 spec, but I would like to use the full absolute path. I know the command line application takes paths with spaces as I also use a batch file with drag and drop which works with spaces in paths. I have tried inserting escapes, etc, still no luck. How can I get this to work properly with full folder paths with spaces?
class SubmissionPane(wx.Panel):
def __init__(self, parent, queue_control):
wx.Panel.__init__(self, parent, -1)
self.parent = parent
self.queue_control = queue_control
self.selected_folder = None
self.txtTitle = wx.TextCtrl(self, pos=(125, 70), size=(215, 25), style= wx.SUNKEN_BORDER, value="Enter Series Title Here")
self.txtTitle.Show(False)
self.drop_target = MyFileDropTarget(self)
self.SetDropTarget(self.drop_target)
def SetSubmissionFolders(self, folder_list):
"""Called by the FileDropTarget when files are dropped"""
print "Setting submission folders", folder_list
self.tc_files.SetValue(','.join(folder_list))
self.selected_folders = folder_list
class MyFileDropTarget(wx.FileDropTarget):
""""""
def __init__(self, window):
wx.FileDropTarget.__init__(self)
print "Creating a drop file target..."
self.window = window
def OnDropFiles(self, x, y, filenames):
self.window.SetSubmissionFolders(filenames)
I then submit this to Popen like this:
command1 = commandLineApplication + folder_list
process = Popen(command1, shell=True, stdin=PIPE)

You probably just need to put quotes around each of the file paths. That usually works. The win32api.GetShortPathName is a neat trick though.
Here's one way to do it:
n = ['"%s"' % x for x in folderlist]
Then do the
','.join(folder_list)
You mentioned in your code.

Related

%3d instead of = in file path, then i try to open file from resources

I write some tests and to get absolute path from relative path i use this function
private def getAbsolutePath(filePath: String): String = {
getClass.getResource(filePath).getFile
}
and then i do:
println(getAbsolutePath("/parquetIncrementalProcessor/withPartitioning/"))
println(getAbsolutePath("/parquetIncrementalProcessor/withPartitioning/own_loading_id=1/partition_column=test/"))
i get:
/Users/19658296/csp-fp-snaphot/library/target/scala-2.11/test-classes/parquetIncrementalProcessor/withPartitioning/
/Users/19658296/csp-fp-snaphot/library/target/scala-2.11/test-classes/parquetIncrementalProcessor/withPartitioning/own_loading_id%3d1/partition_column%3dtest/
As you can see, instead of =, I get some strange symbol. At the same time, when I try to read these files with a park, he can read the path without %3d, and with %3d he gets the error "Path does not exist".
How can I fix this?
Seems like its URL encoded, maybe because using stuff from files and resources are designed to work with Universal Resource Locators. You can URLDecode it like so:
import java.net.URLDecoder
def getAbsolutePath(filePath: String): String = {
val path = getClass.getResource(filePath).getFile
URLDecoder.decode(path, "UTF-8")
}

How to make the platform independent filepath slash "/" with GLib? (GJS)

I have a folderPath which has a directory string:
/home/bastian/Pictures
and I have a variable fileName which contains the name.
I can concatenate the two strings together like this, but it only works on UNIX systems:
let filePath = folderPath + '/' + fileName;
Is there a way with GLib I can concatenate the two to each other without making assumptions about the slash or backslash (to stay fx Windows-compatible)?
With help from guadec, I found out I could use GLib's g_build_filenamev () function.
let filePath = GLib.build_filenamev([folderPath, fileName]);
This builds a path to the file and respects the platform at the same time.
Note: it requires that you import GLib first at the top of your GJS file, like this:
const { GLib } = imports.gi;
If you happen to be using a Gio.File object to manipulate the path, you can also do something like this:
const folder = Gio.File.new_for_path(folderPath);
const file = folder.get_child(fileName);

Compute file content hash with Scala

In our app, we are in need to compute file hash, so we can compare if the file was updated later.
The way I am doing it right now is with this little method:
protected[services] def computeMigrationHash(toVersion: Int): String = {
val migrationClassName = MigrationClassNameFormat.format(toVersion, toVersion)
val migrationClass = Class.forName(migrationClassName)
val fileName = migrationClass.getName.replace('.', '/') + ".class"
val resource = getClass.getClassLoader.getResource(fileName)
logger.debug("Migration file - " + resource.getFile)
val file = new File(resource.getFile)
val hc = Files.hash(file, Hashing.md5())
logger.debug("Calculated migration file hash - " + hc.toString)
hc.toString
}
It all works perfectly, until the code get's deployed into different environment and file file is located in a different absolute path. I guess, the hashing take the path into account as well.
What is the best way to calculate some sort of reliable hash of a file content that well produce the same result for as log as the content of a file stays the same?
Thanks,
Having perused the source code https://github.com/google/guava/blob/master/guava/src/com/google/common/io/Files.java - only the file contents are hashed - the path does not come into play.
public static HashCode hash(File file, HashFunction hashFunction) throws IOException {
return asByteSource(file).hash(hashFunction);
}
Therefore you need not worry about locality of the file. Now why you end up with a different hash on a different fs .. maybe you should compare the size/contents to ensure eg no compound eol's were introduced.

Sed and awk application

I've read a little about sed and awk, and understand that both are text manipulators.
I plan to use one of these to edit groups of files (code in some programming language, js, python etc.) to make similar changes to large sets of files.
Primarily editing function definitions (parameters passed) and variable names for now, but the more I can do the better.
I'd like to know if someone's attempted something similar, and those who have, are there any obvious pitfalls that one should look out for? And which of sed and awk would be preferable/more suitable for such an application. (Or maybe something entirely else? )
Input
function(paramOne){
//Some code here
var variableOne = new ObjectType;
array[1] = "Some String";
instanceObj = new Something.something;
}
Output
function(ParamterOne){
//Some code here
var PartOfSomething.variableOne = new ObjectType;
sArray[1] = "Some String";
var instanceObj = new Something.something
}
Here's a GNU awk (for "gensub()" function) script that will transform your sample input file into your desired output file:
$ cat tst.awk
BEGIN{ sym = "[[:alnum:]_]+" }
{
$0 = gensub("^(" sym ")[(](" sym ")[)](.*)","\\1(ParameterOne)\\3","")
$0 = gensub("^(var )(" sym ")(.*)","\\1PartOfSomething.\\2\\3","")
$0 = gensub("^a(rray.*)","sA\\1","")
$0 = gensub("^(" sym " =.*)","var \\1","")
print
}
$ cat file
function(paramOne){
//Some code here
var variableOne = new ObjectType;
array[1] = "Some String";
instanceObj = new Something.something;
}
$ gawk -f tst.awk file
function(ParameterOne){
//Some code here
var PartOfSomething.variableOne = new ObjectType;
sArray[1] = "Some String";
var instanceObj = new Something.something;
}
BUT think about how your real input could vary from that - you could have more/less/different spacing between symbols. You could have assignments starting on one line and finishing on the next. You could have comments that contain similar-looking lines to the code that you don't want changed. You could have multiple statements on one line. etc., etc.
You can address every issue one at a time but it could take you a lot longer than just updating your files and chances are you still will not be able to get it completely right.
If your code is EXCEEDINGLY well structured and RIGOROUSLY follows a specific, highly restrictive coding format then you might be able to do what you want with a scripting language but your best bets are either:
change the files by hand if there's less than, say, 10,000 of them or
get a hold of a parser (e.g. the compiler) for the language your files are written in and modify that to spit out your updated code.
As soon as it starts to get slightly more complicated you will switch to a script language anyway. So why not start with python in the first place?
Walking directories:
walking along and processing files in directory in python
Replacing text in a file:
replacing text in a file with Python
Python regex howto:
http://docs.python.org/dev/howto/regex.html
I also recommend to install Eclipse + PyDev as this will make debugging a lot easier.
Here is an example of a simple automatic replacer
import os;
import sys;
import re;
import itertools;
folder = r"C:\Workspaces\Test\";
skip_extensions = ['.gif', '.png', '.jpg', '.mp4', ''];
substitutions = [("Test.Alpha.", "test.alpha."),
("Test.Beta.", "test.beta."),
("Test.Gamma.", "test.gamma.")];
for root, dirs, files in os.walk(folder):
for name in files:
(base, ext) = os.path.splitext(name);
file_path = os.path.join(root, name);
if ext in skip_extensions:
print "skipping", file_path;
else:
print "processing", file_path;
with open(file_path) as f:
s = f.read();
before = [[s[found.start()-5:found.end()+5] for found in re.finditer(old, s)] for old, new in substitutions];
for old, new in substitutions:
s = s.replace(old, new);
after = [[s[found.start()-5:found.end()+5] for found in re.finditer(new, s)] for old, new in substitutions];
for b, a in zip(itertools.chain(*before), itertools.chain(*after)):
print b, "-->", a;
with open(file_path, "w") as f:
f.write(s);

Resource Not Found Exception in pyglet

I'm using Python 2.6.6 and pyglet 1.1.4. In my "Erosion" folder, I have "Erosion.py" and a folder named "Images." Inside images, there are .png images. One image is named "Guard.png."
In "Erosion.py" there is a segment that goes like so:
pyglet.resource.path = ['Images']
pyglet.resource.reindex()
self.image = pyglet.resource.image('%s%s' % (character, '.png'))
When I run this, I am given
File "C:\Python26\lib\site-packages\pyglet\resource.py", line 394, in file raise ResourceNotFoundException(name)
ResourceNotFoundException: Resource "Guard.png" was not found on the path. Ensure that the filename has the correct captialisation.
I have tried changing the path to ['./Images'] and ['../Images']. I've also tried removing the path and the reindex call and putting Erosion.py and Guard.png in the same folder.
This is what i do to be able to load resources:
pyglet.resource.path = ['C:\\Users\\myname\\Downloads\\temp']
pyglet.resource.reindex()
pic = pyglet.resource.image('1.jpg')
texture = pic.get_texture()
gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_NEAREST)
texture.width = 960
texture.height = 720
texture.blit(0, 0, 0)
try this
pyglet.image.load('path/to/image.png')
If the relative path is not working you can try with the absolute path using the os module.
import pyglet
import os
working_dir = os.path.dirname(os.path.realpath(__file__))
pyglet.resource.path = [os.path.join(working_dir,'Images')]
pyglet.resource.reindex()
image = pyglet.resource.image('character.png'))
It's better to use the os.path.join method instead of writing it as a string for a better cross-platform support.
I get a problem like this using pyglet and pyscripter.(the text editor) In order for the file to be found I have to restart the editor before running the program.
This might be a problem with pyscripter however.
It is worth looking into: http://pyglet.readthedocs.io/en/pyglet-1.3-maintenance/programming_guide/resources.html
You should include all the directories into:
pyglet.resource.path = [...]
Then pass the ONLY the file name when you call:
pyglet.resource.image("ball_color.jpeg")
Try:
import os
import pyglet
working_dir = os.path.dirname(os.path.realpath(__file__))
image_dir = os.path.join(working_dir, 'images')
sound_dir = os.path.join(working_dir, 'sound')
print working_dir
print "Images are in: " + image_dir
print "Sounds are in: " + sound_dir
pyglet.resource.path = [working_dir, image_dir, sound_dir]
pyglet.resource.reindex()
try:
window = pyglet.window.Window()
image = pyglet.resource.image("ball_color.jpeg")
#window.event
def on_draw():
window.clear()
image.blit(0, 0)
pyglet.app.run()
finally:
window.close()
The use of try and finally are not necessary, but they are recommended. You might end up with a lot of open windows and pyglet back processes if you don't close the window when there are errors.
pyglet 1.4.4 format: HUD_img = pyglet.resource.image('ui\ui_gray_block_filled.png')
pyglet 1.4.8 format: HUD_img = pyglet.resource.image('ui/ui_gray_block_filled.png')
I was using pyglet 1.4.4 and was able to use this the first format.
After upgrading to pyglet 1.4.8 I had the error: pyglet.resource.ResourceNotFoundException: Resource "your_resource_path" was not found on the path.
Switching to the 2nd format with forward slashes solved this issue for me. Not sure why this change was made...I'm sure there was a good reason for it.