开发者

Perl as a batch-script tool - fully piping child processes?

开发者 https://www.devze.com 2023-03-21 20:51 出处:网络
Apologies if some of the terminology may be slighlty off here. Feel free to correct me if I use a wrong term for something.

Apologies if some of the terminology may be slighlty off here. Feel free to correct me if I use a wrong term for something.

Is it possible to use Perl as an "advanced shell" for running "batch" scripts? (on Windows)

The problem I face when replacing a .bat/.cmd script that's getting too complicated with a perl script is that I can't easily run sub processes as a shell does.

That is, I would like to do the same thing from my perl script as a shell does when invoking a child process, that is, fully "connecting" STDIN, STDOUT and STDERR.

Example:

foo.bat -

@echo off
echo Hello, this is a simple script.
set PARAM_X=really-simple

:: The next line will allow me to simply "use" the tool on the shell I have open, 
:: that is STDOUT + STDERR of the tool are displayed on my STDOUT + STDERR and if
:: I enter something on the keyboard it is sent to the tools STDIN

interactive_commandline_tool.exe %PARAM_X%

echo The tool returned %ERROLEVEL%

However, I have no clue how to fully implement this in perl (is it possible at all?):

foo.pl -

print "Hello, this is a not so simple script.开发者_如何转开发\n";
my $param_x = get_more_complicated_parameter();

# Magic: This sub executes the process and hooks up my STDIN/OUT/ERR and 
# returns the process error code when done
my $errlvl = run_executable("interactive_commandline_tool.exe", $param_x);
print "The tool returned $errlvl\n";

How can I achieve this in perl? I played around with IPC::Open3 but it seems this doesn't do the trick ...


Probably you'll find IPC::Run3 useful. It allow you to capture both STDOUT and STDERR (but not pipe them in real time). Command error level will be returned in $?.


Why not this way:

print "Hello, this is a not so simple script.\n";
my $param_x = get_more_complicated_parameter();

system('cmd.exe', $param_x);
my $errorlevel = $? >> 8;
print "The tool returned $errorlevel\n";

sub get_more_complicated_parameter { 42 }

I don't have your interactive program, but the shell executed allowed me to enter commands, it has inherited environment defined in perl, etc.

I am using perl as replacement for more complicated shell scripts on Windows for long time and so far everything I needed was possible.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号