Python子进程Grep [英] Python Subprocess Grep

查看:126
本文介绍了Python子进程Grep的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



这是我的:

  userid ='foo12'
p = subprocess.Popen(['grep',%s * .log%userid],stdout = subprocess.PIPE)

它什么也没有返回。
我不完全确定我做错了什么,所以有人可以解释。我正在使用的当前方法是通过添加shell = true使其输出正确的输出,但由于帮助页面指出它是不安全的。我需要帮助来完成这项工作,以便我的脚本不是不安全的。

解决方案

我认为你遇到了两个问题:


  1. 这个调用:

    pre $ subprocess.Popen(['grep', %s * .log%userid] ...

    $ c> shell = True ,因为参数列表直接传递给 os.execvp ,这要求每个项目都是一个单一的字符串一个参数,你把两个单独的参数压缩成一个单独的字符串(换句话说,grep解释为 foo12 * .log as 模式进行搜索,而不是模式+文件列表)。



    您可以通过以下方式解决此问题:

      p = subprocess.Popen(['grep',userid,'* .log'] ...)
    第二个问题是,同样没有 shell = True ,<$ c $

  2. c> execvp 不知道 *。log 和passe直接与grep配合使用,而不需要通过shell的通配符扩展机制。如果您不想使用 shell = True ,您可以改为执行以下操作:

      import glob 
    args = ['grep',userid]
    args.extend(glob.glob('*。log')
    p = subprocess.Popen(args, ...)



I am trying to use the grep command in a python script using the subprocess module.

Here's what I have:

userid = 'foo12'
p = subprocess.Popen(['grep', "%s *.log"%userid], stdout=subprocess.PIPE)

And it returns nothing. I am not entirely sure what I am doing wrong so can someone please explain. The current method that I am using that works is by adding the shell=true which makes it output the correct output but as the help pages have pointed out it is unsafe. I need help trying to make this work so that my script isn't unsafe.

解决方案

I think you're running up against two problems:

  1. This call:

    p = subprocess.Popen(['grep', "%s *.log"%userid]...
    

    will not work as expected without shell=True because the list of arguments are being passed directly to os.execvp, which requires each item to be a single string representing an argument. You've squished two separate arguments together into a single string (in other words, grep is interpreting "foo12 *.log" as the pattern to search, and not pattern+file list).

    You can fix this by saying:

    p = subprocess.Popen(['grep', userid, '*.log']...)
    

  2. The second issue is that, again without shell=True, execvp doesn't know what you mean by *.log and passes it directly along to grep, without going through the shell's wildcard expansion mechanism. If you don't want to use shell=True, you can instead do something like:

    import glob
    args = ['grep', userid]
    args.extend(glob.glob('*.log')
    p = subprocess.Popen(args, ...)
    

这篇关于Python子进程Grep的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆