本文共 1335 字,大约阅读时间需要 4 分钟。
- 我希望每天固定时间,从某接口获取数据,然后把当天的数据插入到另一个数据库中
- 因为我shell脚本不太熟悉,所以只能把核心的业务逻辑放在python3脚本中
- python3的脚本需要具备一个功能,既能自动执行,也能手动执行。而且手动执行的时候需要传入一个日期参数,方便脚本获取固定日期的数据。
有关crontab的使用基础,可参考博文:
# python my_tools.py arg1 arg2 arg3
import sysargs_list = sys.argv # 获取命令行参数列表,包括执行文件信息length = len(sys.argv) # 命令行参数的个数n = length -1script_info = sys.argv[0] # 脚本的信息print(args_list)print(length)print(script_info)
# 在终端执行: python my_tools.py alien['my_tools.py', 'alien'] 2my_tools.py
$1, $2,..., $N # 分别代表第1个参数,第二个参数,第N个参数$# # 代表了命令行的参数数量$0 #代表了脚本的名字
注意,shell脚本中,如果不传递参数,$#的值会是0
# if 语句基础if [ command ];then 符合该条件执行的语句elif [ command ];then 符合该条件执行的语句else 符合该条件执行的语句fi
#! /bin/bashif [ $# = 1 ] ;thenpython3 /root/shell_file/test_print.py $1elif [ $# = 0 ];thenpython3 /root/shell_file/test_print.pyfi
# 以下内容是核心逻辑,部分函数就不贴出来了,执行的python文件名为:test_print.py t = datetime.date.today() s_today = t.strftime("%Y%m%d") is_open = judge_open_market(pro, s_today) if is_open == 0: print("当前日期:%s----闭市,查不到任何数据" % s_today) elif is_open == 1 and length == 1: hk_hold_ratio_save_to_mysql(pro, s_today) print("当前日期:%s----开市,自动保存数据" % s_today) elif is_open == 1 and length == 2: hk_hold_ratio_save_to_mysql(pro, args_list[1]) print("当前日期:%s----开市,手动保存数据" % s_today)
转载地址:http://ateab.baihongyu.com/