2016-04-01 10 views
0

subprocesspythonスクリプトを実行して名前付き引数を渡しています。は、Pythonでタグのリストを作成する際に問題があります。

Tags=[ 
     { 
      'Key': 'string', 
      'Value': 'string' 
     }, 
    ] 

ここに私の親スクリプトされています:

def call_script(tags): 

    result = subprocess.Popen(["python","second_script.py","--tags",tags]) 
    result.wait() 

if __name__ == '__main__': 

tags = '{' 
    tags = tags + '"Name":"' + username + '"' 
    tags = tags + ', "Designation":"' + Designation + '"' 
    tags = tags + ', "Type":"' + type + '"' 
    tags = tags + '}' 
    tags = str(tags) 

    call_script(tags) 

ここでは私のsecond_script.pyあるsubprocessスクリプトでは、私はその後、そのフォーマットを以下に示しているlist of tagslist of key and value pair)を形成する必要があります:

if __name__ == '__main__': 

    # Initialize tags 
    tags = {} 
    lst = [] 

    # Basic command line argument parsing to launch using boto 
    parser = argparse.ArgumentParser() 

    parser.add_argument('--tags', type=json.loads) 

    args = parser.parse_args() 


    print args.tags 

    # Build a list of tags 
    for k, v in args.tags.iteritems(): 
     print k 
     print v 
     tags['Key'] = k 
     tags['Value'] = v 
     print tags 
     lst.append(tags) 

    # print 'Tags: ',tags 
    print "List of Tags: ",lst 

私はこれを実行すると、 tキーと値のペアは、tagslstの両方にあります。どのように私は上記の希望の形式で示しているようにキーの値のペアのリストを形成することができますか?

サンプル入力があってもよい:

Name: Jason 
Designation: Analyst 
Type: Permanent 

、所望の出力フォーマットがされるべきである:

Tags = [ 
{ 
       'Key': 'Name', 
       'Value': 'Jason' 
      }, 
{ 
       'Key': 'Designation', 
       'Value': 'Analyst' 
      }, 
{ 
       'Key': 'Type', 
       'Value': 'Permanent' 
      }, 
] 

私は上記のコードで取得tagsの出力は - {'Value': u'Permanent', 'Key': u'Type'}lstであるのに対し:[{'Value': u'Permanent', 'Key': u'Type'}, {'Value': u'Permanent', 'Key': u'Type'}, {'Value': u'Permanent', 'Key': u'Type'}]

私のコードに間違いがありますが、どうすれば修正できますか?

答えて

0

は、あなたのforループでtagsをリセットしてください:

for k, v in args.tags.iteritems(): 
    tags={} #changed Line 
    print k 
    print v 
    tags['Key'] = k 
    tags['Value'] = v 
    print tags 
    lst.append(tags) 
0

dictが変更可能であり、あなたがlstに同じオブジェクトへの参照を追加しているためです。

print tags 
lst.append({'Key' : k, 'Value' : v}) 
+0

tags['Key'] = k tags['Value'] = v print tags lst.append(tags) 

を交換してください私はあなたが述べたように、リストを形成することが可能だが、HTTPSに示すように、実際に私が)(AWSのrun_job_flowにこのリストを使用しようとしています://boto3.readthedocs。 org/en/latest/reference/services/emr.html#EMR.Client.run_job_flowとなっており、エラーが発生しています。私は 'タグ'にそれを渡そうとしています。 –

+0

どのようなエラーが表示されますか? –

+0

'botocore.exceptions.ParamValidationError:パラメータの検証に失敗しました: パラメータタグ[0]、値:タイプ:、有効なタイプ: ' –

関連する問題