Is there a way to make an existing cmd window execute commands? - windows

So here is my situtation.
I am using the Windows OS. I am running a Matlab GUI that launches another executable at startup. The other executable runs in batch mode (runs in cmd in the background).
I want to make it so when a user clicks a button on the Matlab GUI, the other executable will run a command and remain open. Is this possible?
NOTE: I do not want to open a new cmd window, I want the existing one to execute commands.

Unfortunately it does not appear that Matlab has the ability you are looking for, at least not directly. I found a post which does explain how to do it with the help of .NET though, which is fortunate since you are on the Windows platform: http://www.mathworks.com/matlabcentral/answers/72356-using-matlab-to-send-strings-to-the-stdin-of-another-console-application
I have copied a lot of this from that post
function lh = task()
% Initialize the process and its StartInfo properties.
% The sort command is a console application that
% reads and sorts text input.
process = System.Diagnostics.Process;
process.StartInfo.FileName = 'sort.exe';
process.EnableRaisingEvents = true;
process.StartInfo.CreateNoWindow = true;
% Set UseShellExecute to false for redirection.
process.StartInfo.UseShellExecute = false;
%Redirect the standard output of the sort command.
process.StartInfo.RedirectStandardOutput = true;
% Set our event handler to asynchronously read the sort output.
lh = process.addlistener('OutputDataReceived',#sortOutputHandler);
% Redirect standard input as well. This stream
% is used synchronously.
process.StartInfo.RedirectStandardInput =true;
% Start the process.
process.Start();
%Use a stream writer to synchronously write the sort input.
ProcessStreamWriter = process.StandardInput;
% Start the asynchronous read of the sort output stream.
process.BeginOutputReadLine();
%Prompt the user for 4 input text lines. Write each
%line to the redirected input stream of the sort command.
numInputLines = 0;
while(numInputLines ~= 4)
inputText = input('Enter a text line (or press the Enter key to stop):', 's');
numInputLines = numInputLines + 1;
if(~isempty(inputText))
ProcessStreamWriter.WriteLine(inputText);
end
end
disp('end of input stream');
%end the inputr stream to the sort command
ProcessStreamWriter.Close();
% wait for the sort process to write the sorted text lines
process.WaitForExit();
process.Close();
end
For handling any output from the CMD you need:
function processOutputHandler(obj,event)
%collect the sort command output and print in command window
if(~isempty(event.Data))
disp(event.Data);
end
end
You can use a stream writer to synchronously write the sort input.
processStreamWriter = process.StandardInput;
Again, I have taken this from the previously mentioned post so I can't take any credit for the code, but I do think it will be able to accomplish what you are looking for. Unfortunately, I am pretty sure this will accomplish what you need. I don't have Matlab on a Windows platform at the moment or I would test this. If you need information on using .NET code in MATLAB (its not immediately clear if you need to add some stuff to establish the .NET interface) MathWorks provides some documentation on it: http://www.mathworks.com/help/matlab/matlab_external/using-net-from-matlab-an-overview.html
Hopefully this helps, or gets you started. Let me know if there's anything else I missed.

You can approach this from the ansys side. Start it with -B-R to read a python script.
From there, you can establish some two-way protocol, for example polling files or, better, by running a web server from python.
Then you can communicate from matlab with that running instance of ansys. If you opt for a web server, you use MATLABs urlread().
Setting up a web-server with python is easy, but you have to learn how to dispatch commands to the hosting ansys application.

Related

How to simulate a TTY while also piping stdio?

I'm looking for a cross-platform solution for simulating a TTY (PTY?) in Rust while also piping stdio.
The frontend is based on web technologies where an interactive terminal is shown. Users can run commands and all their inputs will be sent to the Rust backend, where the commands get executed. Std{in,out,err} are sent back end forth to allow for an interactive experience.
Here's a simplified example (piping only stdout):
let mut child = Command::new(command)
.stdout(Stdio::piped())
.spawn()
.expect("Command failed to start");
loop {
let read = reader.read(&mut chunk);
if let Ok(len) = read {
if len == 0 {
break;
}
let chunk = &chunk[..len];
send_chunk(chunk); // send chunk to frontend
} else {
eprintln!("Err: {}", read.unwrap_err());
}
}
Currently, running the command tty prints: not a tty, but ideally, it should output a file name (e.g /dev/ttys002). And programs, such as atty should return true.
Running only the backend in a terminal, with stdio inherited works, but then I can't send the stdio back to the frontend.
Define "cross platform". As far as PTYs is concerned, those are pseudo devices supported by the kernel, complete with ioctls and everything. As a matter of fact a lot of the things your terminal emulator will have to do, is implementing the receiving end of those ioctls.
As long as you're on a machine with the BSD API (which includes Linux), the best course of action would be to openpty and roll with that. If you want to be portable to non BSD PTY capable systems, you'll have to hook the tty functions in the child process (by preloading a helper library).

Detecting when a subprocess expects input in Ruby

I have a console application (command response type) that I want to control its IO so I can feed it with a script from file and then continue the execution manually when the script execution is finished.
my script is this:
ARGF.readlines = commands
IO.popen('ConsoleApplication') { |io|
begin
puts io.gets
sleep 0.1
end while ????
}
As I observed IO.popen connects the input of io object to the process IO but the output should be read. If by some means the output was displayed automatically or I could detect when the process is waiting for input where ???? is I think I could consider this matter as done!
My further workaround results:
Expect do not work on widows because windows do not support pseudo terminals(PTY) so I can't use ruby_expect like libraries for windows!
I tried IO.select in combination with IO.read_nonblock which encounters "bad file pointer". Some people said that non-blocking IO is not supported in windows as well
So I used some special strings to synchronize the read-write sequences myself and the task is done.

Matlab - signal after command completion

Is there a way to set matlab to come to the foreground of the windows when the command in complete? I can see it happening by executing a dos() but I'm unaware how window management works? Maybe there is a better way? Someone?
Two options. Neither exactly what you are asking for.
Option 1: Open a new figure.
figure();
imagesc(processingDoneSplashImage);
If you want to get fancy, put this in a script, with a timer, and flash the image between bright green, and bright red....
Option 2: My solution to your problem. (I find popping up windows extremely annoying.) I put this function call at the end of my long running scripts, and the computer tells me when it's done processing....
function [ ] = matSpeak( textToSpeak )
%matSpeak takes some text, and outputs onto the speaker the text,
% using the .Net SpeechSynthesizer.
% This only works on Windoze.
if ~exist('textToSpeak','var')
textToSpeak = 'Your processing has completed.';
end
NET.addAssembly('System.Speech');
speak = System.Speech.Synthesis.SpeechSynthesizer;
speak.Volume = 100;
speak.Speak(textToSpeak);
end
Why not just use Growl for your notification windows?
cmd = ['/usr/local/bin/growlnotify -m ' messagestr];
system(cmd);
Of course with Windows you need to fix the path to the growlnotify binary.
Source: http://www.mathworks.com/matlabcentral/newsreader/view_thread/259142
A wrapper with lots of features: Send a notification to Growl on MATLAB Exchange
Many more examples: https://www.google.com/search?q=growl+matlab

how to kill orphaned winword.exe in matlab

Running matlab R2010B on Windows 7 Enterprise
In matlab scripts, I save a bunch of results to a word file and then at the end, close and quit word. The code I use is:
WordFname = ['BatInfoDoc' sprintf('%0.3f',now) '.doc']; % serialnumbered filenames
WordFile = fullfile(pwd,WordFname);
WordApp = actxserver('Word.Application');
WordDoc = WordApp.Documents.Add;
WordDoc.SaveAs2(WordFile);
....
WordApp.Selection.TypeText([title2 title3 title4 title5 title6]);
WordApp.Selection.TypeParagraph;
then finally at the end of the script
WordDoc.Close;
WordApp.Quit;
The problem I have is that through my development process, I often crash the matlab script and wind up leaving orphaned WINWORD.EXE processes, each one of which keeps a lock on the file it had been writing.
Up until now I have been using TaskManager to kill these processes one at a time by hand. Having been developing all morning, I find myself with around 20 files I can't delete because they are locked by about 11 orphaned WINWORD.EXE processes!
My question(s):
1) Is there an elegant way to handle the file writing and saving and closing and so on so I don't lock up files and processes when my script crashes out before I get to the part where I close the file and quit word?
2) Is there an elegant way to determine the bad processes from within matlab script and go through and delete them from within a matlab script? That is, can I code my matlab so it cleans up after itself?
ADDED A FEW MINUTES LATER:
By the way, I would prefer NOT to enclose all my code in a big try-catch and then close the windows after I've caught my error. The problem with this is I do like to go to debug mode on error, and caught errors don't bring me to debug mode.
Straight after you create Wordapp, use c = onCleanup(#()Wordapp.Quit). When your function exits, either naturally or with a crash, c will be deleted and its function will execute, quitting Word. If this is part of a script rather than a function, you can manually delete c to quit.
Also - while developing/debugging, I would set Wordapp.Visible to true so you can manually close word if necessary. Set back to false for production.
Use a handle class to delete them automatically.
classdef SafeWord < handle
properties(Access=public)
WordApp;
end
methods(Access=public)
function this = SafeWord(WordApp)
this.WordApp= WordApp;
end
function delete(this)
this.WordDoc.Close;
this.WordApp.Quit;
end
end
end
And the use case:
sw = SafeWord(Word.Application());
WordApplication = sw.WordApp;
% Do something here
% When sw ends its lifecycle, it calls delete.
Here is a related question.

How to hook into application and process startup in windows?

I am trying to write a program that will hook into application startup and capture the commandline. Don't have an idea where to start as I am pretty green in windows programming.
Would appreciate any help
thanks
You didn't mention your prefered programming language, so I'll use C# for example snippets.
You can start a process and capture/write into its standard IO streams.
The following snippet, opens a process and captures its StdOut stream:
using (var process = Process.Start(new ProcessStartInfo(FileName = #"yourExecutablePath", UseShellExecute = false, RedirectStandardOutput = true)))
using (var stdout = process.StandardOutput)
Console.WriteLine(stdout.ReadToEnd());
EDIT 1
Looks like you want to hook Windows APIs like CreateProcess.
One way to do so is to write a kernel driver and use hooking techniques such as SSTD patching. But writing a kernel driver IMO is cumbersome.
In some cases you can use user-level hooks. There are a few libraries that might help you with that, including: EasyHook, Deviare, and MS Detour.
EDIT 2
You can also use WMI as #David Heffernan suggested but it will only notify you AFTER the process gets started (as opposed to hooking, which allows you to run some arbitrary code BEFORE the hooked function gets called and/or override the function call):
using System.Management;
// Run this in another thread and make sure the event watcher gets disposed before exit
var start = new ManagementEventWatcher(new WqlEventQuery("SELECT * FROM Win32_ProcessStartTrace"));
start.EventArrived += new EventArrivedEventHandler(delegate (object sender, EventArrivedEventArgs e) {
console.WriteLine("Name: {0}, Command Line: {1}", e.NewEvent.Properties["ProcessName"].Value, e.NewEvent.Properties["Commandline"].Value);
});
start.Start()

Resources