如何在python中将对象解析为字符串?

2024-04-19 20:19:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个密码:

from subprocess import call
domain = input('input domain\n>>')
callme = 'whois %s ' % domain
data = call(callme, shell=True)

当我试着

print('TYPE OF DATA\n>>%s' % type(data))

它还给了我

<class 'int'>

我需要操纵返回,但我不能解析这个对象。我试过str()和repr(),然后json.loads文件()但这些都不适合我


Tags: offromimporttrue密码inputdatadomain
1条回答
网友
1楼 · 发布于 2024-04-19 20:19:45

您拥有流程的退出代码。参见^{} documentation

Run the command described by args. Wait for command to complete, then return the returncode attribute.

对于链接的returncode条目:

The child return code, set by poll() and wait() (and indirectly by communicate()).

如果期望进程在stdout上生成输出,则应使用^{},并将stdout设置为subprocess.PIPE,以便用Python读取该输出:

import subprocess

callme = 'whois %s ' % domain
proc = subprocess.run(callme, shell=True, stdout=subprocess.PIPE)
data = proc.stdout

这将为您提供一个bytes对象;您可以设置text=True以获得解码的字符串值。你知道吗

演示:

>>> import subprocess
>>> proc = subprocess.run('whois stackoverflow.com', shell=True, stdout=subprocess.PIPE)
>>> proc.stdout.partition(b'\n')[0]
b'% IANA WHOIS server'
>>> proc = subprocess.run('whois stackoverflow.com', shell=True, stdout=subprocess.PIPE, text=True)
>>> print(*proc.stdout.splitlines()[57:74], sep='\n')
   Domain Name: STACKOVERFLOW.COM
   Registry Domain ID: 108907621_DOMAIN_COM-VRSN
   Registrar WHOIS Server: whois.name.com
   Registrar URL: http://www.name.com
   Updated Date: 2018-01-11T17:50:25Z
   Creation Date: 2003-12-26T19:18:07Z
   Registry Expiry Date: 2019-02-02T11:59:59Z
   Registrar: Name.com, Inc.
   Registrar IANA ID: 625
   Registrar Abuse Contact Email: abuse@name.com
   Registrar Abuse Contact Phone: 7202492374
   Domain Status: clientTransferProhibited https://icann.org/epp#clientTransferProhibited
   Name Server: NS-1033.AWSDNS-01.ORG
   Name Server: NS-358.AWSDNS-44.COM
   Name Server: NS-CLOUD-E1.GOOGLEDOMAINS.COM
   Name Server: NS-CLOUD-E2.GOOGLEDOMAINS.COM
   DNSSEC: unsigned

相关问题 更多 >