不能在子进程命令中使用grep

时间:2018-01-24 09:40:15

标签: python grep subprocess

我的子进程命令有问题,我喜欢把与“在线”行匹配的行格式化。

<?php $sup_terms = get_terms("supplier_categoties", array("orderby" => "slug", "parent" => 0, "hide_empty" => false)); ?>

<!-- Nav tabs -->
<ul class="nav nav-tabs" role="tablist">
    <?php foreach($sup_terms as $key => $sup_term) : ?>
<li role="presentation" class="active"><a href="#<?php echo $sup_term->slug; ?>" aria-controls="<?php echo $sup_term->slug; ?>" role="tab" data-toggle="tab"><?php echo $sup_term->name; ?></a></li>
<?php 
    $tabcontent .='  <div role="tabpanel" class="tab-pane active" id="'.$sup_term->slug.'">...</div>'; // dynamic tab content
endforeach; ?>   </ul>

<!-- Tab panes -->
<div class="tab-content">
    <?php  echo $tabcontent; ?>

</div>

但我会收到错误

def run_command(command):
    p = subprocess.Popen(command,shell=False,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.STDOUT)
    return iter(p.stdout.readline, b'')

command = 'mosquitto_sub -u example -P example -t ITT/# -v | grep "Online" '.split()
for line in run_command(command):
    print(line)

但是在运行linux shell时

Error: Unknown option '|'.



Use 'mosquitto_sub --help' to see usage.

我也试过了user@server64:~/Pythoniscriptid$ mosquitto_sub -u example -P example -t ITT/# -v | grep "Online" ITT/C5/link Online ITT/IoT/tester55/link Online ITT/ESP32/TEST/link Online ,但没有成功,因为我会收到另一个错误,那就是不能识别主题shell = True

ITT/#

“可能的公开”根本没有帮助我,所以我认为我遇到了另一个问题。我试图将代码更改为此,但没有获得任何返回

Error: You must specify a topic to subscribe to.



Use 'mosquitto_sub --help' to see usage.

1 个答案:

答案 0 :(得分:1)

分割文本时,列表将如下所示

['mosquitto_sub', ..., 'ITT/#', '-v', '|', 'grep', '"Online"']

当您将此列表传递给subprocess.Popen时,文字'|'将成为mosquitto_sub的参数之一。

如果您使用shell=True,则必须在命令中转义任何特殊字符,例如#,例如使用双引号:

import subprocess
command = 'echo -e "ITT/#\\ni am Online\\nbar Online\\nbaz" | grep "Online" '
p = subprocess.Popen(
    command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
for line in iter(p.stdout.readline, b''):
    print(line)

或者,在编写时连接管道,但请确保迭代到b'',而不是u''

import subprocess

def run_command(command, command2):
    p1 = subprocess.Popen(command,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
    p2 = subprocess.Popen(command2,stdin=p1.stdout,stdout=subprocess.PIPE)
    return iter(p2.stdout.readline, b'')

command = ['echo', '-e', 'ITT/#\\ni am Online\\nbar Online\\nbaz']
command2 = 'grep Online'.split()

for line in run_command(command,command2):
    print(line)