小编dob*_*bbs的帖子

在 Python 中动态创建嵌套字典

试图了解如何即时创建嵌套字典。理想情况下,我的字典看起来像:

mydict = { 'Message 114861156': { 'email': ['user1@domain.com', 'user2@domain.com'] }, { 'status': 'Queued mail for delivery' }} 
Run Code Online (Sandbox Code Playgroud)

这是我到目前为止所拥有的:

sampledata = "Message 114861156 to user1@domain.com user2@domain.com  [InternalId=260927844] Queued mail for delivery'."

makedict(sampledata)

def makedict(results):
  newdict = {}
  for item in results:
    msgid = re.search(r'Message \d+', item)
    msgid = msgid.group()
    newdict[msgid]['emails'] = re.findall(r'\w+@\w+\.\w+', item)
    newdict[msgid]['status'] = re.findall(r'Queued mail for delivery', item)
Run Code Online (Sandbox Code Playgroud)

有以下输出:

Traceback (most recent call last):
  File "wildfires.py", line 57, in <module>
    striptheshit(q_result)
  File "wildfires.py", line 47, in striptheshit
    newdict[msgid]['emails'] …
Run Code Online (Sandbox Code Playgroud)

python dictionary

7
推荐指数
1
解决办法
8618
查看次数

python嵌套列表/字典和弹出值

事先道歉,这是一个新手问题.我刚刚开始编写python,我一直对嵌套字典/列表中的弹出值感到困惑,所以我感谢任何帮助!

我有这个示例json数据:

{ "scans": [
   { "status": "completed", "starttime": "20150803T000000", "id":533},
   { "status": "completed", "starttime": "20150803T000000", "id":539}
] }
Run Code Online (Sandbox Code Playgroud)

我想从"扫描"键中弹出"id".

def listscans():
  response = requests.get(scansurl + "scans", headers=headers, verify=False)
  json_data = json.loads(response.text)
  print json.dumps(json_data['scans']['id'], indent=2)
Run Code Online (Sandbox Code Playgroud)

似乎没有工作,因为嵌套的键/值在列表中.即

>>> print json.dumps(json_data['scans']['id'])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not str
Run Code Online (Sandbox Code Playgroud)

任何人都可以指出我正确的方向让这个工作?我的长期目标是创建一个for循环,将所有id放入另一个我可以用于另一个函数的字典或列表中.

python dictionary nested-lists

5
推荐指数
1
解决办法
3054
查看次数

Python 线程:多个 While True 循环

你们对以下应用程序使用哪些 python 模块有任何建议:我想创建一个运行 2 个线程的守护进程,两个线程都带有while True:循环。

任何例子将不胜感激!提前致谢。

更新:这是我想出的,但行为不是我所期望的。

import time
import threading

class AddDaemon(object):
    def __init__(self):
        self.stuff = 'hi there this is AddDaemon'

    def add(self):
        while True:
            print self.stuff
            time.sleep(5)


class RemoveDaemon(object):
    def __init__(self):
        self.stuff = 'hi this is RemoveDaemon'

    def rem(self):
        while True:
            print self.stuff
            time.sleep(1)

def run():
    a = AddDaemon()
    r = RemoveDaemon()
    t1 = threading.Thread(target=r.rem())
    t2 = threading.Thread(target=a.add())
    t1.setDaemon(True)
    t2.setDaemon(True)
    t1.start()
    t2.start()
    while True:
        pass

run()
Run Code Online (Sandbox Code Playgroud)

输出

Connected to pydev debugger (build 163.10154.50)
hi this …
Run Code Online (Sandbox Code Playgroud)

python multithreading daemon python-daemon

5
推荐指数
1
解决办法
1万
查看次数

boto3 列出与 ec2 实例关联的安全组

是否可以列出与 EC2 实例关联的所有安全组boto3?如果是这样,这是怎么做的?

我尝试了以下方法,但他们没有做我想做的事:

for region in regions:
    client = boto3.client('ec2', region_name=region)
    try:
        payload = client.describe_security_groups(Filters=[{'Name': 'vpc-id', 'Values': ['vpc-*']}])
        for sg in payload["SecurityGroups"]:
            if sg["Description"] != "default VPC security group":
                resp = client.describe_security_group_references(DryRun=False, GroupId=[sg["GroupId"]])
                print resp

    except Exception as E:
        print region, E
        continue
Run Code Online (Sandbox Code Playgroud)
for region in regions:
    client = boto3.client('ec2', region_name=region)
    try:
        payload = client.describe_security_groups(Filters=[{'Name': 'vpc-id', 'Values': ['vpc-*']}])
        for sg in payload["SecurityGroups"]:
            if sg["Description"] != "default VPC security group":
                sg = json.dumps(sg)
                pp(sg)
                # x = requests.post(url=sumocollector, …
Run Code Online (Sandbox Code Playgroud)

python amazon-ec2 boto3

4
推荐指数
1
解决办法
3059
查看次数

要列出的 Python 嵌套元组

我有一个 mysql 查询,它运行并选择与 select 语句匹配的所有 Id:

first_seen_select = "SELECT Id FROM domains_archive WHERE current_epoch = " + current_epoch + " AND first_seen IS NULL"
cur.execute(first_seen_select)
Run Code Online (Sandbox Code Playgroud)

的输出cur.fetchall()

((1,), (2,), (3,), (4,), (5,), (6,), (7,))
Run Code Online (Sandbox Code Playgroud)

我如何提取这些嵌套的元组 Id # 并将它们转换为我可以迭代的单个列表?

如果我运行以下我得到:

>>> bleh = cur.fetchall()
>>> for i in bleh:
...   print(i)
... 
(1,)
(2,)
(3,)
(4,)
(5,)
(6,)
(7,)
Run Code Online (Sandbox Code Playgroud)

python mysql

3
推荐指数
1
解决办法
1620
查看次数

带有预旋转脚本的条件 logrotate

我的集群中有两台 syslog-ng 服务器(热/冷),它们都映射相同的 NFS 共享。我想在 syslog 服务器上运行 logrotate 以轮换存储在 NFS 共享上的日志。问题是,目前如果两个节点都有/etc/logrotate.d/syslog-ng配置,就会导致双重旋转。

我认为必须有一种方法可以使用prerotate节来logrotate.d确定轮换是否应该在服务器上发生。换句话说,如果被动节点尝试运行logrotateprerotate脚本将首先检查该节点是否为主节点。如果它不是主要的,我希望prerotate脚本在运行之前进行处理exitlogrotate

有人能指出正确的方向来弄清楚如何使logrotate prerotate脚本成为exit其父logrotate进程吗?

bash logrotate

3
推荐指数
1
解决办法
5387
查看次数

PowerShell for-each循环输出到文件

如何将此foreach循环的内容输出/附加到文本文件?

以下内容无法解决.

$Groups = Get-AdGroup -Properties * -filter * | Where {$_.name -like "www*"}
Foreach($G in $Groups)
{
    write-host " "
    write-host $G.Name
    write-host "----------"
    get-adgroupmember -Identity $G | select-object -Property SamAccountName
    Out-File -filepath C:\test.txt -Append
}
Run Code Online (Sandbox Code Playgroud)

powershell

2
推荐指数
1
解决办法
1万
查看次数

AWS IAM 找到具有特定策略的角色?

有点像 AWS IAM 的新手。有没有办法找到给定帐户中附加了特定策略的所有可用角色?即,如果您只知道策略,而不知道它附加到的角色,那么如何找到给定策略附加的所有角色?

amazon-web-services amazon-iam

0
推荐指数
1
解决办法
1832
查看次数