execute time period in python
<p>I want to run the script in shell by sending time period like</p>

<pre><code>./test.py 20160830000 201608311100
</code></pre>

<p>How can I do this for the following python script?
<code>s</code> and <code>t</code> are UNIX timestamp.</p>

<pre><code>#!/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)
</code></pre>

<p>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 <code>date</code> using the deprecated <code>commands</code> module, rather than using Python's builtin <code>time</code> or <code>datetime</code> modules, which can handle timestamps and dates natively).</p>

<p>This is quite easy. The command line arguments to a Python script are stored in the list <code>sys.argv</code>. 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!</p>

<p>Try something like this:</p>

<pre><code># 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
</code></pre>

<p>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.</p>

python json linux