将参数传递给cURL shell脚本文件

时间:2015-02-01 02:34:02

标签: python shell curl command-line-arguments

我对shell或python脚本没有多少经验,所以我正在寻找一些有关如何实现这一目标的帮助。

目标:

将参数传递给shell或python脚本文件,该文件将用于执行cURL Post请求或python post请求。

我们说我去了python路线,文件名是api.py

import json,httplib
connection = httplib.HTTPSConnection('api.example.com', 443)
connection.connect()
connection.request('POST', '/message', json.dumps({
       "where": {
         "devicePlatform": "andriod"
       },
       "data": {
         "body": "Test message!",
         "subject": "Test subject"
       }
     }), {
       "X-Application-Id": "XXXXXXXXX",
       "X-API-Key": "XXXXXXXX",
       "Content-Type": "application/json"
     })
result = json.loads(connection.getresponse().read())
print result

我如何通过参数传递主体和主题值以及如何通过命令行查看?

由于

2 个答案:

答案 0 :(得分:1)

尝试使用argparse来解析命令行参数

from argparse import ArgumentParser
import json

import httplib

parser = ArgumentParser()
parser.add_argument("-s", "--subject", help="Subject data", required=True)
parser.add_argument("-b", "--body", help="Body data", required=True)
args = parser.parse_args()
connection = httplib.HTTPSConnection('api.example.com', 443)
connection.connect()
connection.request('POST', '/message', json.dumps({
       "where": {
         "devicePlatform": "andriod"
       },
       "data": {
         "body": args.body,
         "subject": args.subject,
       }
...

在CLI上它看起来像

python script.py -b "Body" -s "Subject"

答案 1 :(得分:0)

使用argparse。主题的一个例子:

import json,httplib
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('subject', help='string containing the subject')
args = parser.parse_args()

connection = httplib.HTTPSConnection('api.example.com', 443)
connection.connect()
connection.request('POST', '/message', json.dumps({
       "where": {
         "devicePlatform": "andriod"
       },
       "data": {
         "body": "Test message!",
         "subject": args.subject
       }
     }), {
       "X-Application-Id": "XXXXXXXXX",
       "X-API-Key": "XXXXXXXX",
       "Content-Type": "application/json"
     })
result = json.loads(connection.getresponse().read())
print result