subproces.Popen 使用或“|”符号不起作用

问题描述 投票:0回答:1

我正在尝试仅列出 Wi-Fi 网络适配器的 IP 地址,以便能够检测它是否已连接并附加有 IP 地址。

仅靠这个它就可以工作......

from subprocess import Popen

Popen([
    'netsh',
    'interface',
    'ip',
    'show',
    'addresses',
    'Wi-Fi'
]).communicate()

输出:

Configuration for interface "Wi-Fi"
    DHCP enabled:                         No
    IP Address:                           192.168.1.200
    Subnet Prefix:                        192.168.1.0/24 (mask 255.255.255.0)
    Default Gateway:                      192.168.1.1
    Gateway Metric:                       0
    InterfaceMetric:                      2

但是,有了这个...

from subprocess import Popen

Popen([
    'netsh',
    'interface',
    'ip',
    'show',
    'addresses',
    'Wi-Fi',
    '|',
    'findstr',
    '/ir',
    'IP Address'
]).communicate()

列表中带有 或

|
符号,它正在生成此...

Usage: show addresses  [[name=]<string>]

Parameters:

       Tag         Value
       name      - The name or index of a specific interface.

Remarks: Displays the IP address configuration for an interface or
         interfaces.

The information displayed for this command consists of:

Field              Description
-----              -----------
DHCP enabled       Shows whether the address comes from static or DHCP
                   configuration.
IP Address         Shows the IP address configured for an interface.
Subnet Mask        Shows the subnet mask associated with the IP address.
Default Gateway    Shows the IP address of a default gateway for the interface.
Gateway Metric     Shows the metric for the default gateway shown above.
                   Only applies if multiple default gateways are configured.
Interface Metric   Shows the metric for an interface.
                   Only applies if multiple interfaces are configured.

Examples:

       show addresses "Wired Ethernet Connection"

表明我输入了错误的适配器名称。

我尝试了列表中

netsh
参数的多种组合,但没有任何运气。

有人对此有任何见解吗?

我目前最好的猜测是 Popen 不知道如何处理 或

|
符号。

python subprocess popen
1个回答
0
投票

我认为您的输出流设置不正确。当我运行你的代码时,我得到:

Configuration for interface "Wi-Fi"\
...my network info here...

None

当我删除你的打印语句时,我没有得到

None
打印输出,但网络信息仍然打印......所以看起来你的
stdout
var 被设置为
None

我自己进行了一些谷歌搜索,我想出了以下可以让你摆脱困境的方法:

from subprocess import PIPE, Popen

command = [
    'netsh',
    'interface',
    'ip',
    'show',
    'addresses',
    'Wi-Fi',
    '|',
    'findstr',
    '/ir',
    'IP Address'
]
with Popen(command, stdout=PIPE, stderr=None, shell=True) as process:
    output = process.communicate()[0].decode("utf-8")
    print(output)

这会产生:

IP Address:                           <My-IP>

不完全确定您的代码有什么问题,但如果我从 Popen 调用中删除

shell=True
,我会得到与您相同的错误。

© www.soinside.com 2019 - 2024. All rights reserved.