哪一个python函数可以帮助我从一长段输出中只提取一行输出?

2024-10-03 11:12:48 发布

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

最近,我一直在试用python来帮助我从python文件中运行Mac终端命令,特别是尝试查看我的设备上的蓝牙是打开还是关闭的。以下是我一直使用的代码:

#!/usr/bin/env python3
import os
import subprocess

p = subprocess.run('sudo defaults read /Library/Preferences/com.apple.Bluetooth ', shell=True, check=True, capture_output=True, text=True)
print(p.stdout, p.stderr)

但是,通常情况下,我会收到一个长输出,如下所示:

{
    BluetoothAccStatus = 0;
    BluetoothVersionNumber = 6;
    ControllerPowerState = 1;
    "D2D MAC Address" = {length = 6, bytes = 0x0200693eab66};
    PersistentPorts =     {
        "incoming port - Bluetooth-Incoming-Port" =         {
            BTAuthenticationRequired = 0;
            BTEncryptionType = 0;
            BTName = "incoming port - Bluetooth-Incoming-Port";
            BTPSM = 3;
            BTRFCOMMChannel = 3;
            BTSerialConnectionType = 0;
            BTTTYName = "Bluetooth-Incoming-Port";
            HiddenPort = 1;
            IOTTYBaseName = "Bluetooth-Incoming-Port";
            P49SerialPort = 1;
        };
    };

但是,我打算只获取该输出中的前两行,它们是BluetoothAccStatus(检查我的机器上是否打开或关闭了蓝牙)和BluetoothVersionNumber(混淆地显示了我安装的LMP版本的蓝牙)

是否有一个功能可以可靠地完成这项工作


Tags: 文件代码import命令true终端portmac
1条回答
网友
1楼 · 发布于 2024-10-03 11:12:48

你可以使用这行代码或者这个函数,在这里你可以输入你的整个段落,以及你想得到多少行作为输出

s1="Python was invented by Guido van Rossum. Python is a object oriented programming 
language. Python has over 100 of libraries."
s2=''
n=int(input("How many lines you wanna get?\n"))
i=0
for j in s1:
    if j!='.':
        s2+=j
    else:
        s2+='.'
        i+=1
    if i==n:
        break
print(s2)

输出: 你想打多少线

一,

Python是由Guido van Rossum发明的

相关问题 更多 >