简体   繁体   中英

execute time period in python

I want to run the script in shell by sending time period like

./test.py 20160830000 201608311100

How can I do this for the following python script? s and t are UNIX timestamp.

#!/usr/bin/python
import requests
from pprint import pprint
import json
import os
import commands
i =  commands.getstatusoutput('date -d "2016-08-30" "+%s"')
j =  commands.getstatusoutput('date -d "2016-08-31" "+%s"')
s = int(i[1])
t = int(j[1])
url = 'http://192.168.1.96/zabbix/api_jsonrpc.php'
payload = {
    "jsonrpc": "2.0",
    "method": "history.get",
    "params": {
        "output": "extend",
        "history": 0,
        "time_from": s,
        "time_till": t,
        "hostsids": "10105",
        "itemids": "23688",
        "sortfield": "clock",
        "sortorder": "DESC"
    },
    "auth": "b5f1f71d91146fcc2980e83e8aacd637",
    "id": 1
}

header = {
    'content-type': 'application/json-rpc',
}
res  = requests.post(url, data=json.dumps(payload, indent=True), headers=header)
res = res.json()
pprint(res)

If I understand correctly, you want to get the timestamps to use in your jsonrpc call from the command line arguments, rather than using hardcoded dates (which for some reason you're processing through the command line too date using the deprecated commands module, rather than using Python's builtin time or datetime modules, which can handle timestamps and dates natively).

This is quite easy. The command line arguments to a Python script are stored in the list sys.argv . The first value in the list is the filename of the script, the rest are the arguments. You may need to check that there are the expected number of them!

Try something like this:

# your other imports here
import sys

USAGE_MSG = "Usage: test.py START_TIMESTAMP END_TIMESTAMP"
if len(sys.argv) != 3:
    print(USAGE_MSG)
    sys.exit(1)

try:
    s = int(sys.argv[1])
    t = int(sys.argv[2])
except TypeError: # couldn't convert one of the timestamps to int
    print("Invalid timestamp")
    print(USAGE_MSG)
    sys.exit(1)

# the rest of your code can go here

There are a lot of alternative ways you could handle the error checking, I just made something up for this example. You should of course use whatever works best for your needs.

看一看的时间蟒模块,特别是time.strptime用于解析人类可读串时间到时的结构和功能time.mktime用于转换时间结构为Unix时间戳功能。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM