【问题标题】:Executing command and storing output in array variable执行命令并将输出存储在数组变量中
【发布时间】:2015-03-03 12:22:44
【问题描述】:
p = Popen(our_cmd, shell=True, stdout=PIPE, stderr=PIPE)
output = p.communicate()[0]
split = output.strip('\n\t\r').split("\n")

我想执行字符串our_cmd中的这个命令

我试过的是这个

my @output = `$our_cmd`; ## here command is executing
my @split = grep(s/\s*$//g, @output); ## the format and putting in new array
@split = split("\n", @split);

我的命令正在执行,但没有正确输入。我需要像 Python 代码一样以数组格式输出。

【问题讨论】:

  • 你能举一些你正在解析的输出的例子吗?
  • @AlessandroDaRugna:在那个 Python 代码中,stderr 的返回码和内容被忽略了
  • 您的 Python 代码在内存中累积 stderr,然后在最后将其丢弃。要从 shell 命令中获取标准输出行作为列表并丢弃其标准错误:lines = check_output(out_cmd, shell=True, stderr=DEVNULL).splitlines()

标签: python perl popen


【解决方案1】:

据我所知,您所需要的只是

my @split = `$our_cmd`;
chomp @split;

【讨论】:

  • 我不确定strip - 我认为它似乎删除了一些字符?
  • @Sobrique:它正在删除字符串开头和结尾的所有制表符、换行符和回车符。否则split 将在末尾返回一个空字符串。
【解决方案2】:

我认为您在这里误解了几个 perl 概念。例如 - 你在 split 输入一个数组 - 这没有多大意义,因为 split 根据分隔符将 string 转换为一个数组。

同样grep - 这是grep 的不寻常用法,因为您嵌入了搜索和替换模式 - 通常grep 用于基于一些布尔表达式进行过滤。 (我怀疑它是这样工作的,但我不完全确定您的替换模式是否返回真/假,这会在grep 上下文中做奇怪的事情)。

那么不如来代替:

my @output = `$our_command`;

chomp @output; #removes linefeeds from each element. 

for ( @output ) { s/[\t\r]//g; }; #removes linefeeds and carriage returns

这将在@output 每行放入一个元素(包括换行符),然后删除其中的任何\t\r。如果您不想要换行符,正如 Borodin 所说 - chomp @output; 会处理这个问题。

如 cmets 中所述 - 这可能无法完全重现 strip 正在做的事情,并且 strip 操作在 perl 中可能无关紧要。

测试你的 grep:

my @test =  ( "test aaa bbb", "mooo", " aaa Moo MMOoo", "no thing in it" );
print join ("\n", grep { s/aaa//g } @test );

确实$_grep 的每一行)上进行搜索和替换,但替换表达式确实返回“真/假” - 这意味着您有效地丢弃了根本不包含模式。

【讨论】:

  • Python 代码仅从输出的第一行开头和最后一行结尾删除这些字符。无论如何都不应该有任何 CR 字符。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多