简体   繁体   English

如何获取Windows命令行字符串?

[英]how to get windows command line string?

I made a simple executable ( string.exe ) from the following code. 我从以下代码制作了一个简单的可执行文件( string.exe )。 You can not change this file. 您无法更改此文件。

$| = 1;
foreach my $i (1..10) {
    print "test : $i\r";
    sleep 2;
}

I want grab the output from that program in real-time. 我想实时获取该程序的输出。 I attempted to do so with the following code: 我尝试使用以下代码进行操作:

open(my $fh, '-|', 'string.exe') or die $!;
while (my $line = <$fh>) {
    print $line;
}

But I can not get the output in real-time. 但是我无法实时获得输出。 In my opinion, this is due to the use of carriage return ( \\r ). 我认为,这是由于使用了回车符( \\r )。

readline ( <> ) reads until a line feed is encountered, but you send carriage returns instead. readline<> )读取直到遇到换行符,但发送回车键代替。 readline is somewhat configurable (via $/ ), but not to the point where you can instruct it to read until a CR or LF is returned. readline在某种程度上是可配置的(通过$/ ),但是直到您可以指示它读取直到返回CR或LF为止。

sysread , otoh, returns as soon as data is available. 数据可用后,立即返回sysread ,otoh。 This is exactly what you want. 这正是您想要的。

$| = 1;
while (sysread($fh, my $buf, 64*1024)) {
    print $buf;
}

You can set your $INPUT_RECORD_SEPARATOR to \\r : 您可以将$INPUT_RECORD_SEPARATOR设置为\\r

local $/ = "\r";
while (my $line = <$fh>) {

how to get windows command line string? 如何获取Windows命令行字符串?

If I understand your question, you could use something like 如果我了解您的问题,您可以使用类似

local $cmd = join " ", $0, @ARGV;
print $cmd;

Testing choroba 's answer about the $INPUT_RECORD_SEPARATOR : 测试choroba关于$INPUT_RECORD_SEPARATOR的答案:

use strict;
use warnings;

# As described in http://perldoc.perl.org/perlipc.html#Safe-Pipe-Opens
my $pid = open(KID_TO_READ, "-|") // die "can't fork: $!";

# Parent
if ($pid) {
    local $/ = "\r";
    while (<KID_TO_READ>) {
        use Data::Dump;
        dd $_;
    }
    close(KID_TO_READ) or warn "kid exited $?";

# Child
} else {
    local $| = 1;
    foreach my $i (1..10) {
        print "test : $i\r";
        sleep 2;
    }
    exit;
}

Outputs: 输出:

"test : 1\r"
"test : 2\r"
"test : 3\r"
"test : 4\r"
"test : 5\r"
"test : 6\r"
"test : 7\r"
"test : 8\r"
"test : 9\r"
"test : 10\r"

Ironically, this test won't work on Windows: 具有讽刺意味的是,此测试无法在Windows上运行:

'-' is not recognized as an internal or external command,
operable program or batch file.
kid exited 256 at test_RS.pl line 14.

However, this still confirms that the $RS will work as documented. 但是,这仍然确认$RS将按文档所述工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM