Dcode
Dcode

Reputation: 223

Control windows command prompt via tcl

I am launching command prompt as: eval exec [auto_execok start] &

It returns me the pid, and launches command prompt. Can I control the launched shell? Or is there any other way.

Right now I am sending command at the time of launch like: eval exec [auto_execok start] "cd Desktop" &

But I want to control the shell for further operations.

Upvotes: 0

Views: 1701

Answers (2)

kostix
kostix

Reputation: 55573

I suspect you're trying to reinvent a batch file the hard way.

If you need to perform a series of tasks using cmd.exe, spawn it using

set cmd [open |cmd.exe "r+"]

and then simply write your batch script to that stream:

puts $cmd $myscript

To explain: shells (Tcl's own tclsh and wish included) usually have two modes of execution: interactive and non-interactive. The fisrt is enabled when the shell is started "as is", the second—when it's started in a pipeline1. In interactive mode, the shell would display you its prompt and accept commands—interactively. In a non-interactive mode, it will just read commands on its standard input stream and execute them as it reads them. The cmd.exe of Windows is no exception, so you can open |cmd.exe it in "read/write" mode (r+) and write the script composed in its batch command language to its standard input stream which will be bound to the stream object open returns.

If a process started with open or exec writes anything to its standard error stream and/or quits with a non-zero exit code, those commands will raise an exception (that is, error handling is mostly covered for you).


1 Well, for Windows, it's harder to define what "interactive" vs "non-interactive" means, but it's somewhat irrelevant to the question at hand.

Upvotes: 0

Donal Fellows
Donal Fellows

Reputation: 137807

You can't control anything launched that way (other than whatever you can do with the pid); it's specifically requesting to have no control at all with the & at the end.

Some programs can be controlled somewhat when they are launched as pipelines.

set pipeline [open |cmd "r+"]
fconfigure $pipeline -buffering line -blocking 0
puts $pipeline "dir"
while {![fblocked $pipeline]} {
    set line [gets $pipeline]
    puts "I have read: $line"
}

Even more control can be done via Expect, an extension package.

However, the command prompt window can't be controlled by either of these mechanisms; most programs that open windows can't.

Upvotes: 2

Related Questions