以下是脚本的摘录(未经测试)
def start_custer():
try:
myidentifier=mydict['DescribeClustersResponse']['DescribeClustersResult']['Clusters'][0]['ClusterIdentifier']
except IndexError:
conn.restore_from_cluster_snapshot('vi-mar5-deliveryreport-new', mysnapidentifier, availability_zone='us-east-1a')
def stop_cluster():
try:
myidentifier=mydict['DescribeClustersResponse']['DescribeClustersResult']['Clusters'][0]['ClusterIdentifier']
conn.delete_cluster(myidentifier, skip_final_cluster_snapshot=False, final_cluster_snapshot_identifier=myvar)
except:
print "error"
这些功能在技术上(语法上)是否正确?
如何在调用python脚本时调用它们?我需要一次启动或停止群集,而不是两者。
答案 0 :(得分:4)
对于第二个问题,我将通过argparse
解析命令行:
import argparse
parser = argparse.ArgumentParser(description="Manage the cluster")
parser.add_argument("action", choices=["stop", "start"],
help="Action to perform")
args = parser.parse_args()
if args.action == "start":
start_cluster()
if args.action == "stop":
stop_cluster()
答案 1 :(得分:2)
其他人向您展示了执行此操作的最佳方法,但是对于记录,您还可以从命令行执行此操作:
python -c "import cluster; cluster.start_cluster()"
(假设您的模块文件名为cluster.py
- 如果没有,则相应地调整import
语句。
这不像自己解析命令行这样用户友好,但它会在紧要关头完成。
答案 2 :(得分:1)
1)如果您已在某处定义Syntactically
并导入它,则conn
正确无误!
2)
def stop_cluster():
## Your code
def fun():
## your code
if __name__ == "__main__":
import sys
globals()[sys.argv[1]]()
用法:
python2.7 test_syn.py fun
答案 3 :(得分:1)
我在你的脚本中添加了一个main函数来检查命令行参数,然后在没有提供有效参数的情况下提示你:
import sys
def start_custer():
try:
myidentifier=mydict['DescribeClustersResponse']['DescribeClustersResult']['Clusters'][0]['ClusterIdentifier']
except IndexError:
conn.restore_from_cluster_snapshot('vi-mar5-deliveryreport-new', mysnapidentifier, availability_zone='us-east-1a')
def stop_cluster():
try:
myidentifier=mydict['DescribeClustersResponse']['DescribeClustersResult']['Clusters'][0]['ClusterIdentifier']
conn.delete_cluster(myidentifier, skip_final_cluster_snapshot=False, final_cluster_snapshot_identifier=myvar)
except:
print "error"
def main():
valid_args, proc = ['start','stop'], None
# check if cmd line args were passed in (>1 as sys.argv[0] is name of program)
if len(sys.argv) > 1:
if sys.argv[1].lower() in valid_args:
proc = sys.argv[1].lower()
# if a valid arg was passed in this has been stored in proc, if not prompt user
while not proc or proc not in valid_args:
print "\nPlease state which procedure you want to call, valid options are:", valid_args
proc = raw_input('>>> ').lower()
# prompt user if invalid
if proc not in valid_args:
print proc, 'is not a valid selection.'
if proc == 'start':
start_custer()
elif proc == 'stop':
stop_cluster()
# this makes the script automatically call main when starting up
if __name__ == '__main__':
main()
你可以从命令行调用它,例如如果您与文件位于同一目录中(例如名为cluster_ctrl.py):
python cluster_ctrl.py start