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

passing arguments to a cURL shell script file

我对 shell 或 python 脚本没有太多经验,因此我正在寻求有关如何完成此任务的帮助。

目标:

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

假设我走 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

我将如何为正文和主题值传递参数以及通过命令行看起来如何?

谢谢

使用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

尝试使用 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"