How can I issue carriage returns after a system call in MATLAB? - matlab

Context: In a large program built mostly in MATLAB, I am calling a program to display some information to the user, like so:
batchCommand = ['"', programPath, '" ', '"', inputPath, '"'];
system(batchCommand);
Here's the issue: the program at programPath opens two consecutive splash screens, which require the user to press enter in order to bypass. That really busts up the flow of my program, and I'd like to do away with it. There is no option to run the program without the splash screens. The splash screens are in-focus, so pressing return clears them with no further input. So, I'd like to have MATLAB issue a couple of carriage returns for me.
Here's the catch: the system command halts execution of MATLAB code until the opened program is closed. I need to work around this in some way to get those returns issued.
I've tried working with -echo, to no avail.
Has anyone out there done this, or know how to?

Related

waitbar matlab before start a standalone script

I did a standalone application in Matlab and it works. The only problem is that when I launch the application, it takes time before start asking to the user some file (it is the first think the program has to do). The user does not understand if the program is working or not, since no message neither symbol of working progress appear on the screen.
My idea is to show a waitbar until the window asking the file to user appears.
How can I do this? is it possible to use the waitbar outside a loop?
The script starts as follow:
close all
clear all
[filename,pathname] = uigetfile({'*.xlsx'},'Opening File','C:\');
I don't know why, it takes time before open the window for choosing the file.
The time between launch and file selection input appearing is most likely due to the time it takes to load the MCR. You could add a splash screen to your compilation.
If the end user is running from a command line wrap your exe in a system/shell which writes to the command window that the application is starting.
Your issue is most likely the use of clear all. This makes MATLAB remove all variables (in scope, global and persistent), and compiled scripts from memory, forcing it to recompile and load everything again.
If your purpose is to clear all variables in the current scope, you should be able to increase the initial speed of your script by only running clear instead.
Even faster speed can be achieved if you specify which variables to clear using clear var1 var2 ...

programmatically press an enter key after starting .exe file in Matlab

In Matlab I can start external .exe files that sometime have a pop up that requires an enter key pressed. For example:
system('C:\Program Files (x86)\WinZip\WINZIP32.EXE')
will start Winzip, and then in order to use it you need to pass the "buy now" pop up window by pressing enter.
Now my problem is not with winzip, I only gave it as an example (i use winrar anyway :).
How can I programmatically press an enter key in Matlab in such cases ? (I use win 7)
Can an event listener be used to solve that?
EDIT: The java.awt.Robot class indeed works on explorer, but not on any software that has a pop up window with an OK button that needs to be pressed. I don't know why it doesn't work for that. I gave the winzip example because I assume everybody has winzip/winrar installed in their machine. The actual software I have is different and irrelevant for the question.
There is a way using Java from Matlab, specifically the java.awt.Robot class. See here.
Apparently there are two types of programs, regarding the way they work when called from Matlab with system('...'):
For some programs, Matlab waits until the program has finished before running the next statement. This happens for example with WinRAR (at least in my Windows 7 machine).
For other programs this doesn't happen, and Matlab proceeds with the next statement right after the external program has been started. An example of this type is explorer (the standard Windows file explorer).
Now, it is possible to return execution to Matlab immediately even for type 1 programs: just add & at the end of the string passed to system. This is standard in Linux Bash shell, and it also works in Windows, as discussed here.
So, you would proceed as follows:
robot = java.awt.Robot;
command = '"C:\Program Files (x86)\WinRAR\WinRAR"'; %// external program; full path
system([command ' &']); %// note: ' &' at the end
pause(5) %// allow some time for the external program to start
robot.keyPress (java.awt.event.KeyEvent.VK_ENTER); %// press "enter" key
robot.keyRelease (java.awt.event.KeyEvent.VK_ENTER); %// release "enter" key
If your applications are only on Windows platform, you can try using .net objects.
The SendWait method of the SendKeys objects allows to send virtually any key, or key combination, to the application which has the focus, including the "modifier" keys like Alt, Shift, Ctrl etc ...
The first thing to do is to import the .net library, then the full syntax to send the ENTER key would be:
NET.addAssembly('System.Windows.Forms');
System.Windows.Forms.SendKeys.SendWait('{ENTER}'); %// send the key "ENTER"
If you only do it once the full syntax is OK. If you plan to make extensive use of the command, you can help yourself with an anonymous helper function.
A little example with notepad
%% // import the .NET assembly and define helper function
NET.addAssembly('System.Windows.Forms');
sendkey = #(strkey) System.Windows.Forms.SendKeys.SendWait(strkey) ;
%% // prepare a few things to send to the notepad
str1 = 'Hello World' ;
str2 = 'OMG ... my notepad is alive' ;
file2save = [pwd '\SelfSaveTest.txt'] ;
if exist(file2save,'file')==2 ; delete(file2save) ; end %// this is just in case you run the test multiple times.
%% // go for it
%// write a few things, save the file then close it.
system('notepad &') ; %// Start notepad, without matlab waiting for the return value
sendkey(str1) %// send a full string to the notepad
sendkey('{ENTER}'); %// send the {ENTER} key
sendkey(str2) %// send another full string to the notepad
sendkey('{! 3}'); %// note how you can REPEAT a key send instruction
sendkey('%(FA)'); %// Send key combination to open the "save as..." dialog
pause(1) %// little pause to make sure your hard drive is ready before continuing
sendkey(file2save); %// Send the name (full path) of the file to save to the dialog
sendkey('{ENTER}'); %// validate
pause(3) %// just wait a bit so you can see you file is now saved (check the titlebar of the notepad)
sendkey('%(FX)'); %// Bye bye ... close the Notepad
As explained in the Microsoft documentation the SendKeys class may have some timing issues sometimes so if you want to do complex manipulations (like Tab multiple times to change the button you actually want to press), you may have to introduce a pause in your Matlab calls to SendKeys.
Try without first, but don't forget you are managing a process from another without any synchronization between them, so timing all that can require a bit of trial and error before you get it right, at least for complex sequences (simple one should be straightforward).
In my case above for example I am running all my data from an external hard drive with an ECO function which puts it into standby, so when I called the "save as..." dialog, it takes time for it to display because the HDD has to wake up. If I didn't introduce the pause(1), sometimes the file path would be imcomplete (the first part of the path was send before the dialog had the focus).
Also, do not forget the & character when you execute the external program. All credit to Luis Mendo for highlighting it. (I tend to forget how important it is because I use it by default. I only omit it if I have to specifically wait for a return value from the program, otherwise I let it run on its own)
The special characters have a special code. Here are a few:
Shift +
Control (Ctrl) ^
Alt %
Tab {TAB}
Backspace {BACKSPACE}, {BS}, or {BKSP}
Validation {ENTER} or ~ (a tilde)
Ins Or Insert {INSERT} or {INS}
Delete {DELETE} or {DEL}
Text Navigation {HOME} {END} {PGDN} {PGUP}
Arrow Keys {UP} {RIGHT} {DOWN} {LEFT}
Escape {ESC}
Function Keys {F1} ... {F16}
Print Screen {PRTSC}
Break {BREAK}
The full list from Microsoft can be found here
There is a small javascript utility that simulates keystrokes like this on the Windows javascript interpreter.
Just create a js file with following code:
var WshShell = WScript.CreateObject("WScript.Shell");
WshShell.SendKeys(WScript.Arguments(0));
then call it from Matlab after the necessary timeout like this:
system('c:\my\js\file\script.js {Enter}');
Can't test here now, but I think this should work...
If you need to run a console-only program in a context that permits full DOS redirection, you can create a file called, say, CR.txt containing a carriage return and use the '<' notation to pipe the value into the program.
This only works if you can provide all the keyboard input can be recorded in the file. It fails dismally if the input has to vary based on responses.
An alternative is to duplicate the input (and possibly output) stream(s) for the program and then pipe data into and out of the program. This is more robust and can permit dynamic responses to the data, but will also likely require substantial effort to implement a robot user to the application.
Rog-O-Matic is an example of a large application completely controlled by a program that monitors screen output and simulates keyboard input to play an early (1980s) ASCII graphic adventure game.
The other responses will be required for GUI-based applications.
Python package pywinauto can wait any dialog and click buttons automatically. But it's capable for native and some .NET applications only. You may have problems with pressing WPF button (maybe QT button is clickable - not checked), but in such case code like app.DialogTitle.wait('ready').set_focus(); app.DialogTitle.type_keys('{ENTER}') may help. Your case is quite simple and probably some tricks with pywinauto are enough. Is your "app with popup" 64-bit or 32-bit?
wait and wait_not functions have timeout parameter. But if you need precisely listener with potentially infinite loop awaiting popups, good direction is global Windows hooks (pyHook can listen mouse and keybd events, but cannot listen dialog opening). I'll try to find my prototype that can detect new windows. It uses UI Automation API event handlers... and... ops... it requires IronPython. I still don't know how to set UI Automation handler with COM interface from standard CPython.
EDIT (2019, January): new module win32hooks was implemented in pywinauto a while ago. Example of usage is here: examples/hook_and_listen.py.

How to stop a Matlab script but don’t kill the process? [duplicate]

This question already has answers here:
Stop and continue execution from debugger possible?
(6 answers)
Closed 8 years ago.
Strg+C stops and kills a Matlab script (at least sometimes). But is there a way to stop a Matlab, take a look at some variables and continue the calculation?
I am not talking about just setting a breakpoint. I want my script, let’s say run for couple hours come back to it hit some buttons that stops the calculations take a look at some variable and then continue the calculation.
I tried to find out if there is some shortcut key for this – I am quite sure there isn’t.
Now I was thinking about including an if-case that looks if a certain button was pressed by the user. If so there would be a useless k=0 line and a breakpoint on it. And if no one is pressing this button the loop would continue. But this is where my limited Matlab knowledge leaves me. I don’t know if there is a way to ask for a user-button press but don’t wait for a button press like in the function input. Also I just have a running script, I don’t have any GUI.
To drop to the command prompt you need the command keyboard and then type return when you have finished (you don't need a breakpoint). The tricky bit is how to trigger it. There a few options. The easiest is to open a figure window. The following code halts the process when any key is pressed.
keyDownListener=#(src,event) keyboard;
fig = figure;
drawnow
set(fig,'KeyPressFcn',keyDownListener)
for p=1:10000
%do some thing
end
You can modify this to test for a specific key since the keypress is contained within the event struct.
To use no figure gui at all its more of a problem. I'm not aware of a non blocking keyboard input method. A mex file the runs kbhit() in C might do it, but kbhit() is not standard C so it would only work on Windows. An easier option maybe to test for the presence of a file.
for p=1:100000
if exist(fullfile(pwd,'halt.tmp'),'file')
keyboard
end
%do something here
end
This drops to the debug console when halt.tmp is created in the current directory.
Other potential methods could involve using multiple threads to read 'input' (either the Parallel computer toolbox or undocumented Java code), or using http://psychtoolbox.org/ as mentioned by #bdecaf

Disable auto-scrolling in command window

A lot of the code that I write in Matlab has a very verbose output. As the program runs, information is printed to the command window, and with each new line, the window automatically scrolls to the bottom. This becomes a problem when I want to read some of the output more closely or scroll up to look at older output. I can scroll up, but only until a new line is printed, which is often less than a second.
Does anyone know if it is possible to turn off this automatic scrolling in the Matlab window? I work in a number of different Matlab versions, depending on the machine, and this happens with all of them. The answer to this might be "No", but I swear I remember having this functionality at one point.
Use the more function: http://www.mathworks.com/help/matlab/ref/more.html
more on
Then run your program. Press spacebar when you wish to see more of the output.
more off will turn it off.
You may find this workaround useful.
First launch matlab using the command line matlab -logfile 'myLog.txt' (the doc says it "starts MATLAB and makes a copy of any output to the Command Window in filename. This includes all crash reports.")
Then open your .txt file using a text editor supporting automatic refresh of content (see picture). On OSX I use TextWrangler (freely available at www) but others have been reported to have this feature (see here or here).
Results: output displays (fprintf, disp, but not the commands per se) are printed both on the Matlab console and the text editor (file is refreshed with a little lag time, below half a second I would say with my configuration). And there is no automatic scrolling. Such procedure does not seem to impact the overall performance of the script (although it may deserve some testing).

What is the usual way in MATLAB to read help page by page?

I'm looking for an equivalent of for example DOS's dir |more which lists the data, until one page is complete, then waits for a key to be pressed until showing another. Is there an equivalent for MATLAB's help system.
I know I could simply scroll back, but this would be so much more convenient, expecially if one uses help system often.
Type more on at the command line. This will print command outputs page by page.
For the next line: 'return'; next page; 'spacebar'; return to command line: 'q'.
Likewise, more off resumes the normal display mode.