Is it possible to use the GUI library in JythonMusic to create an open/save file dialog. If not is it possible to use an open file window in Tkinter or PyQT in conjunction with jythonMusic?
JythonMusic's GUI library is built on top of Java Swing. So, in principle, you can access all Swing functionality.
The code below does what you ask (and demonstrates the approach).
Do notice how readable the code is, compared to the Java original - http://www.java2s.com/Code/Java/Swing-JFC/DemonstrationofFiledialogboxes.htm
This is partially due to the economy of Python syntax, but also due to the JythonMusic GUI library, which was designed to simplify GUI creation (for most tasks).
# openFileDialogDemo.py
#
# Demonstrates how to create an open/save file dialog in Jython Music.
#
# Based on http://www.java2s.com/Code/Java/Swing-JFC/DemonstrationofFiledialogboxes.htm
#
from gui import *
# create display to hold open button
d = Display("Open Dialog Demo", 200, 50)
filename = None # holds selected filename (if any)
directory = None # holds directory of selected filename (if any)
# set up what to do when open button is pressed
def openButtonAction():
global filename, directory # we will update these
chooser = JFileChooser() # the open dialog window
# here is the only tricky part - accessing the GUI Display's internal JFrame, d.display
returnValue = chooser.showOpenDialog( d.display )
# check what choice user made, and act appropriately
if returnValue == JFileChooser.APPROVE_OPTION:
filename = chooser.getSelectedFile().getName()
directory = chooser.getCurrentDirectory().toString()
print "Filename =", filename
print "Directory =", directory
elif returnValue == JFileChooser.CANCEL_OPTION:
print "You pressed cancel"
# create open button and add it to display
openButton = Button("Open", openButtonAction)
d.add(openButton, 70, 12)
Hope this helps.
Related
I create an executable based on a gui with several functions and files, and if I open the executable in the installation folder or using the desktop shortcut everything works fine. If I open through the starting menu, the executable doesn't incorporate the images and doesn’t run. What I can do to prevent this issue? Is it possible to prevent the shortcut in the windows starting menu?
I found a solution here:
You can use the following function to get the folder of the executed exe file:
function currentDir = getcurrentdir()
if isdeployed % Stand-alone mode.
[status, result] = system('path');
currentDir = char(regexpi(result, 'Path=(.*?);', 'tokens', 'once'));
else % MATLAB mode.
currentDir = pwd;
end
Call the function and use cd in the GUI opening function:
currentDir = getcurrentdir();
cd(currentDir);
I created a guide testing application, and used deploytool for compiling and packaging for external deployment.
For testing, I added a text label to the GUI (Tag name: text2).
In the GUI opening function I added the following code:
% --- Executes just before GuideApp is made visible.
function GuideApp_OpeningFcn(hObject, eventdata, handles, varargin)
handles.output = hObject;
handles.text2.String = 'Starting...';
pause(1);
currentDir = getcurrentdir();
%Set the label's text to display currentDir.
handles.text2.String = currentDir;
%Change directory to the directory of the exe file.
cd(currentDir);
%Create a file in the directory (just for testing):
f = fopen('currentDir.txt', 'w');fprintf(f, '%s\r\n', currentDir);fclose(f);
% Update handles structure
guidata(hObject, handles);
The above solution is working correctly:
The text of label displays the path of the exe file.
currentDir.txt file is created in the path of the exe file.
On windows, MZ/PE executables often have an attibute called "Original File Name", used to describe the original file name assigned to an executable file when it was created.
It is readable to a Windows user from the "Details" tab of the file's "Properties" window (opened by rightclicking a file and selecting "Properties").
I found many other questions that discuss "original file name, so to make it clear, I'm talking about this field, for the mspaint.exe file:
I however, whould like to access/read this attribute (and potentially edit it) using batch files or the windows command line (not powershell, please!).
Thanks!
Windows does not have a built-in command line tool to read version information from PE files.
You can use a resource editor like Resource Hacker to export information but you still have to parse the exported file.
On WinVista+ (and WinXP with desktop search installed) you can read the information using the shell property system (the same API used by the file properties dialog).
A Microsoft developer has created a free tool called shellproperty.exe that you can use to read the System.OriginalFileName property.
With Windows Script Host it is also possible to access the property system if you use the ShellFolderItem.ExtendedProperty method.
And finally, a WSH script can be merged with a batch file to create a working polyglot with zero external dependencies:
#if (1 == 0) #end /*
#cscript.exe /E:jscript /nologo "%~f0" %*
#goto :eof
*/
var objShell = new ActiveXObject("shell.application");
var objFolder2, ssfSysDir = 0x25, propVal = "";
objFolder2 = objShell.NameSpace(ssfSysDir);
if (objFolder2 != null)
{
var objFolderItem;
objFolderItem = objFolder2.ParseName("mspaint.exe");
if (objFolderItem != null)
{
propVal = objFolderItem.ExtendedProperty("{0CEF7D53-FA64-11D1-A203-0000F81FEDEE},6");
WScript.Echo(propVal);
}
}
I would like to determine the OS X keyboard layout (or "input source" as OS X calls it) from the terminal so that I can show it in places like the tmux status bar.
So I want to know if the current layout is "U.S." or "Swedish - Pro" for example.
Googling turns up nothing for me. Is this possible?
Note: #MarkSetchell deserves credit for coming up with the fundamental approach - where to [start to] look and what tools to use.
After further investigation and back and forth in the comments I thought I'd summarize the solution (as of OS X 10.9.1):
do shell script "defaults read ~/Library/Preferences/com.apple.HIToolbox.plist \\
AppleSelectedInputSources | \\
egrep -w 'KeyboardLayout Name' | sed -E 's/^.+ = \"?([^\"]+)\"?;$/\\1/'"
Note how \ is escaped as \\ for the benefit of AppleScript, which ensures that just \ reaches the shell. If you want to execute the same command directly from the shell (as one line), it would be:
defaults read ~/Library/Preferences/com.apple.HIToolbox.plist AppleSelectedInputSources | egrep -w 'KeyboardLayout Name' |sed -E 's/^.+ = \"?([^\"]+)\"?;$/\1/'
The currently selected keyboard layout is stored in the user-level file ~/Library/Preferences/com.apple.HIToolbox.plist, top-level key AppleSelectedInputSources, subkey KeyboardLayout Name.
defaults read ensures that the current settings are read (sadly, as of OSX 10.9, the otherwise superior /usr/libexec/PlistBuddy sees only a cached version, which may be out of sync).
Since defaults read cannot return an individual key's value, the value of interest must be extracted via egrep and sed - one caveat there is that defaults read conditionally uses double quotes around key names and string values, depending on whether they are a single word (without punctuation) or not.
Update:
Turns out that AppleScript itself can parse property lists, but it's a bit like pulling teeth.
Also, incredibly, the potentially-not-fully-current-values problem also affects AppleScript's parsing.
Below is an AppleScript handler that gets the current keyboard layout; it uses a do shell script-based workaround to ensure that the plist file is current, but otherwise uses AppleScript's property-list features, via the Property List Suite of application System Events.
Note: Obviously, the above shell-based approach is much shorter in this case, but the code below demonstrates general techniques for working with property lists.
# Example call.
set activeKbdLayout to my getActiveKeyboardLayout() # ->, e.g., "U.S."
on getActiveKeyboardLayout()
# Surprisingly, using POSIX-style paths (even with '~') works with
# the `property list file` type.
set plistPath to "~/Library/Preferences/com.apple.HIToolbox.plist"
# !! First, ensure that the plist cache is flushed and that the
# !! *.plist file contains the current value; simply executing
# !! `default read` against the file - even with a dummy
# !! key - does that.
try
do shell script "defaults read " & plistPath & " dummy"
end try
tell application "System Events"
repeat with pli in property list items of ¬
property list item "AppleSelectedInputSources" of ¬
property list file plistPath
# Look for (first) entry with key "KeyboardLayout Name" and return
# its value.
# Note: Not all entries may have a 'KeyboardLayout Name' key,
# so we must ignore errors.
try
return value of property list item "KeyboardLayout Name" of pli
end try
end repeat
end tell
end getActiveKeyboardLayout
Recently I had written a small console utility (https://github.com/myshov/xkbswitch-macosx) on Objective-C to do this. It's a lot faster than a script based solutions. It can to get the current input layout but also it can to set the given input layout.
To get a current layout:
$xkbswitch -ge
> US
To set a given layout:
$xkbswith -se Russian
I am not sure of this answer, but it may be worth checking out. If you look in file:
/Library/Preferences/com.apple.HIToolbox.plist
there is a variable called
AppleCurrentKeyboardLayoutSourceID
and mine is set to "British" and I am in Britain...
You can read the file in a script with:
defaults read /Library/Preferences/com.apple.HIToolbox.plist AppleEnabledInputSources
sample output below:
(
{
InputSourceKind = "Keyboard Layout";
"KeyboardLayout ID" = 2;
"KeyboardLayout Name" = British;
}
)
So, I guess your question can be simply answered using this:
#!/bin/bash
defaults read /Library/Preferences/com.apple.HIToolbox.plist AppleEnabledInputSources | grep -sq Swedish
[[ $? -eq 0 ]] && echo Swedish
This question led to the creation of the keyboardSwitcher CLI Tool:
https://github.com/Lutzifer/keyboardSwitcher
Though similar to the already mentioned https://github.com/myshov/xkbswitch-macosx this has additional features, e.g. the list of Layouts is not hardcoded and thus can also support third party layouts (e.g. Logitech) and supports installation via homebrew.
Figured out how to do it with AppleScript, assuming you have the menu bar input menu.
Run this in a terminal:
osascript -e 'tell application "System Events" to tell process "SystemUIServer" to get the value of the first menu bar item of menu bar 1 whose description is "text input"'
Works fine even if you only show the input menu as flag icons, without the input source name.
Mavericks will probably prompt you to allow access, the first time. In earlier versions of OS X I suspect you'll need to turn on support for assistive devices in your accessibility preferences.
I was searching for an answer to an issue I was having with the keyboard layout that lead me to this post. I found the solution for my problem here.
Resolved Issues
You might experience difficulty logging into your account because the keyboard layout may change unexpectedly at the
Login window. (40821875)
Workaround: Log in to your account, launch Terminal, and execute the
following command:
sudo rm -rf /var/db/securityagent/Library/Preferences/com.apple.HIToolbox.plist
This is an Apple official release note for Mojave
I have about 150 .xls and .xlsx files that I need converting into tab-delimited. I tried using automator, but I was only able to do it one-by-one. It's definitely faster than opening up each one individually, though. I have very little scripting knowledge, so I would appreciate a way to do this as painlessly as possible.
If you would be prepared to use Python for this I have written a script that converts Excel spreadsheets to csv files. The code is available in Pastebin.
You would just need to change the following line:
writer = csv.writer(fileout)
to:
writer = csv.writer(fileout, delimiter="\t")
to make the output file tab delimited rather than the standard comma delimited.
As it stands this script prompts you for files one at a time (allows you to select from a dialogue), but it could easily be adapted to pick up all of the Excel files in a given directory tree or where the names match a given pattern.
If you give this a try with an individual file first and let me know how you get on, I can help with the changes to automate the rest if you like.
UPDATE
Here is a wrapper script you could use:
#!/usr/bin/python
import os, sys, traceback
sys.path.insert(0,os.getenv('py'))
import excel_to_csv
def main():
# drop out if no arg for excel dir
if len(sys.argv) < 2:
print 'Usage: Python xl_csv_wrapper <path_to_excel_files>'
sys.exit(1)
else:
xl_path = sys.argv[1]
xl_files = os.listdir(xl_path)
valid_ext = ['.xls', '.xlsx', '.xlsm']
# loop through files in path
for f in xl_files:
f_name, ext = os.path.splitext(f)
if ext.lower() in valid_ext:
try:
print 'arg1:', os.path.join(xl_path,f)
print 'arg2:', os.path.join(xl_path,f_name+'.csv')
excel_to_csv.xl_to_csv(os.path.join(xl_path,f),
os.path.join(xl_path,f_name+'.csv'))
except:
print '** Failed to convert file:', f, '**'
exc_type, exc_value, exc_traceback = sys.exc_info()
lines = traceback.format_exception(exc_type, exc_value, exc_traceback)
for line in lines:
print '!!', line
else:
print 'Sucessfully conveted', f, 'to .csv'
if __name__ == '__main__':
main()
You will need to replace the :
sys.path.insert(0,os.getenv('py'))
At the top with an absolute path to the excel_to_csv script or an environment variable on your system.
Use VBA in a control workbook to loop through the source workbooks in a specified directory or a list of workbooks, opening each, saving out the converted data, then closing each in turn.
Is there a way to get a local timestamp in my IPython prompt? I'm using IPython 0.10 and Python 2.6 on 64-bit Windows Vista.
My current default prompt is
[C:Python26/Scripts]
|9>
OK, I tried to follow your directions exactly. However, my experience has been that all config editing is best kept to my ipy_user_conf.py. To quote from it:
User configuration file for IPython (ipy_user_conf.py)
This is a more flexible and safe way to configure ipython than *rc files
(ipythonrc, ipythonrc-pysh etc.)
This file is always imported on ipython startup. You can import the
ipython extensions you need here (see IPython/Extensions directory).
Feel free to edit this file to customize your ipython experience.
Note that as such this file does nothing, for backwards compatibility.
Consult e.g. file 'ipy_profile_sh.py' for an example of the things
you can do here.
See http://ipython.scipy.org/moin/IpythonExtensionApi for detailed
description on what you could do here.
So I now have these lines in main():
# -- prompt
# A different, more compact set of prompts from the default ones, that
# always show your current location in the filesystem:
o.prompt_in1 = r'\C_LightBlue[\C_LightCyan\Y2\C_LightBlue]\C_Normal\n\C_Green|\#>'
o.prompt_in2 = r'.\D: '
o.prompt_out = r'[\#] '
And I get this, for an example:
16:49:50 In[9]:1/7
1 [9] 0.14285714285714285
16:50:09 In[10]:
Questions:
What is that 1?
How can I keep the current directory in the prompt? Before, I had
[C:Python26/Scripts]
|8>
Once more with feeling.
I'm so sorry for the mess I've made. I need to report the lines I either added or modified actually are:
import_all("os sys random datetime")
o.prompt_in1 = r'\C_LightBlue[\C_LightCyan\Y2\C_LightBlue]\C_Normal\n\C_Green|\#>'
o.prompt_in1 = r'${datetime.now().strftime("%H:%M:%S")}[\#]:'
o.prompt_out = r'[\#] '
The easiest way is to edit your ipythonrc (in your home\_ipython directory), and add these lines:
import_mod datetime
prompt_in1 '${datetime.datetime.now()} In [\#]: '
# or
prompt_in1 '${datetime.datetime.now().strftime("%H:%M:%S")} In [\#]: '
Alternatively, you can also just add the import_mod datetime to the rc file, and add this to the main() function of ipy_user_conf.py (in the same directory):
o = ip.options
o.prompt_in1 = r'${datetime.datetime.now()} In [\#]: '
# or
o.prompt_in1 = r'${datetime.datetime.now().strftime("%H:%M:%S")} In [\#]: '