python – 来自subprocess.Popen的输出
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python – 来自subprocess.Popen的输出,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含3050字,纯文字阅读大概需要5分钟。
内容图文
![python – 来自subprocess.Popen的输出](/upload/InfoBanner/zyjiaocheng/791/8094e007cfe94c69b566240c728b7bf8.jpg)
我一直在编写一些python代码,在我的代码中我使用的是“命令”
代码按照我的意图工作,但后来在Python文档中注意到该命令已被弃用,将在Python 3中删除,我应该使用“subprocess”代替.
“好的”我想,“我不希望我的代码直接进入遗留状态,所以我现在应该改变它.
问题是subprocess.Popen似乎在任何输出的开头加上一个令人讨厌的字符串,例如
<subprocess.Popen object at 0xb7394c8c>
我看到的所有例子都有它,它似乎被接受,因为它始终存在.
这段代码;
#!/usr/bin/python
import subprocess
output = subprocess.Popen("ls -al", shell=True)
print output
产生这个;
<subprocess.Popen object at 0xb734b26c>
brettg@underworld:~/dev$total 52
drwxr-xr-x 3 brettg brettg 4096 2011-05-27 12:38 .
drwxr-xr-x 21 brettg brettg 4096 2011-05-24 17:40 ..
<trunc>
这是正常的吗?如果我将它作为一个更大的程序的一部分,它将各种格式化的细节输出到控制台,它会让一切都变得混乱.
我正在使用该命令获取接口的IP地址,方法是使用ifconfig以及各种greps和awks来获取地址.
考虑这段代码;
#!/usr/bin/python
import commands,subprocess
def new_get_ip (netif):
address = subprocess.Popen("/sbin/ifconfig " + netif + " | grep inet | grep -v inet6 | awk '{print $2}' | sed 's/addr://'i", shell=True)
return address
def old_get_ip (netif):
address = commands.getoutput("/sbin/ifconfig " + netif + " | grep inet | grep -v inet6 | awk '{print $2}' | sed 's/addr://'i")
return address
print "OLD IP is :",old_get_ip("eth0")
print ""
print "NEW IP is :",new_get_ip("eth0")
这回来了;
brettg@underworld:~/dev$./IPAddress.py
OLD IP is : 10.48.16.60
NEW IP is : <subprocess.Popen object at 0xb744270c>
brettg@underworld:~/dev$10.48.16.60
至少可以说这很难看.
显然我在这里遗漏了一些东西.我当然是Python的新手,所以我确信这是我做错了事,但各种谷歌搜索在这一点上毫无结果.
如果我想要清洁输出怎么办?我是否必须手动修剪有问题的输出或我是否正在调用subprocess.Popen?
提前致谢!
解决方法:
“丑陋的字符串”就是应该打印的东西. Python正确地打印出repr(subprocess.Popen(…)),就像你说print(open(‘myfile.txt’))时打印的那样.
此外,python不知道输出到stdout的内容.您看到的输出不是来自python,而是来自进程的stdout和stderr被重定向到您的终端作为垃圾邮件,甚至没有通过python进程.这就像你运行程序someprogram&没有将其stdout和stderr重定向到/ dev / null,然后尝试运行另一个命令,但你偶尔会看到程序中的垃圾邮件.重复和澄清:
<subprocess.Popen object at 0xb734b26c> <-- output of python program
brettg@underworld:~/dev$total 52 <-- spam from your shell, not from python
drwxr-xr-x 3 brettg brettg 4096 2011-05-27 12:38 . <-- spam from your shell, not from python
drwxr-xr-x 21 brettg brettg 4096 2011-05-24 17:40 .. <-- spam from your shell, not from python
...
要捕获stdout,必须使用.communicate()函数,如下所示:
#!/usr/bin/python
import subprocess
output = subprocess.Popen(["ls", "-a", "-l"], stdout=subprocess.PIPE).communicate()[0]
print output
此外,你永远不想使用shell = True,因为它是一个安全漏洞(一个主要的安全漏洞,带有未经过输入的输入,一个没有输入的次要漏洞,因为它通过修改shell环境允许本地攻击).出于安全原因以及避免错误,您通常希望传入列表而不是字符串.如果你很懒,你可以做“ls -al”.split(),这是不赞成的,但是做一些像(“ls -l%s”%unsanitizedInput).split()这样的安全漏洞.
内容总结
以上是互联网集市为您收集整理的python – 来自subprocess.Popen的输出全部内容,希望文章能够帮你解决python – 来自subprocess.Popen的输出所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。