如何通过正则表达式运行Popen命令的运行输出

时间:2017-10-17 04:59:30

标签: python regex subprocess popen

我尝试使用Popen执行命令,并使用正则表达式搜索输出以查找UserID。当我运行下面的代码并注释掉if reg_ex.search(line)代码块时,该命令成功运行(尽管我没有我的userID)。一旦我取消注释正则表达式代码,命令本身就会失败。

任何想法为什么这个正则表达式if语句使命令本身失败,当我只是迭代输出和任何想法如何从输出获得我需要的userId?我已经确认正则表达式本身在单独运行时有效(尽管对于那些需要它的人来说,正则表达式的输出行看起来像这样u'userId': u'userID_in–question'}

import re
import subprocess

#command I want to run
command = "add-user " + FirstName + " " + LastName + " " + Email + " " + Phone

#Regex to find userId in output
reg_ex_find = re.compile('userId')
reg_ex_replace = re.compile("(""u'userId""|\s|:|}|')")

#call command
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, 
stderr=subprocess.PIPE)

for line in iter(process.stdout.readline, b''):
     print line
     if reg_ex_find.search(line):
            UserId = line
            reg_ex_replace.sub('',UserId) 
process.stdout.close()
process.wait()
print process.returncode

0 个答案:

没有答案
相关问题