Python 中的转义转义序列
我对 python 有点陌生。目标是使用子进程解析和执行 shell 命令。从 shell 检索打印输出。执行错误如下面的示例输出消息所示。下面还显示了示例代码片段
代码片段:
testStr = "cat tst.txt | grep Location | sed -e '/.*Location: //g' "
print "testStr = "+testStr
testStrOut = subprocess.Popen([testStr],shell=True,stdout=subprocess.PIPE).communicate()[0]
输出:
testStr = cat tst.txt | grep Location | sed -e '/.*Location: //g'
cat: tst.txt: No such file or directory
sed: -e expression #1, char 15: unknown command: `/'
是否有解决方法或可以使用的函数?
感谢您的帮助 谢谢
I am kind of new to python. Goal is to execute a shell command using subprocess parse & retrive the printed output from shell. The execution errors out as shown in the sample output msg below. Also shown below is the sample code snippet
Code snippet:
testStr = "cat tst.txt | grep Location | sed -e '/.*Location: //g' "
print "testStr = "+testStr
testStrOut = subprocess.Popen([testStr],shell=True,stdout=subprocess.PIPE).communicate()[0]
Output:
testStr = cat tst.txt | grep Location | sed -e '/.*Location: //g'
cat: tst.txt: No such file or directory
sed: -e expression #1, char 15: unknown command: `/'
Is there a workaround or a function that could be used ?
Appreciate your help
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我想你的主要错误与 python 无关。更准确地说,有 3 个:
导入子流程
。///g
而不是s///g
。tst.txt
不存在。I suppose your main error is not python related. To be more precise, there are 3 of them:
import subprocess
.sed -e 's/.*Location: //g'
. You wrote///g
instead ofs///g
.tst.txt
does not exist.您应该直接传递 testStr 作为第一个参数,而不是将其包含在列表中。请参阅 subprocess.Popen,以“在 Unix 上,使用 shell”开头的段落=正确:...”。
You should be passing testStr directly as the first argument, rather than enclosing it in a list. See subprocess.Popen, the paragraph that starts "On Unix, with shell=True: ...".