[英]Python script - how to pass password as variable from command line arguments
I am running a REST call using python to generate a access token.我正在使用 python 运行 REST 调用来生成访问令牌。 The REST call payload has password value.
REST 调用有效负载具有密码值。 I dont want to hardcode the password there but pass it as an option while running the python script.
我不想在那里对密码进行硬编码,而是在运行 python 脚本时将其作为选项传递。 Below is the payload inside the python script.
下面是 python 脚本中的有效负载。
payload = "grant_type=client_credentials&client_id=userid&client_secret=password&scope=AppIdClaimsTrust&intent=RequestLink"
Currently I exectute the script by python script.py目前我通过python script.py执行脚本
Set the token as an environment variable:将令牌设置为环境变量:
$ export TOKEN=XXXXXXX
Then using the os
library:然后使用
os
库:
#!/usr/bin/env python
import os
token = os.environ['TOKEN']
Use token
where you would normally hard code it into your script.在通常会将其硬编码到脚本中的地方使用
token
。
Alternatively, you could pass it as a command line argument .或者,您可以将其作为命令行参数传递。
$ python script.py XXXXXXXX
In your script, access the token using:在您的脚本中,使用以下命令访问令牌:
#!/usr/bin/env python
import sys
if len(sys.argv) > 1:
token = sys.argv[1]
else:
print("No token passed")
You can use this using sys.argv
.您可以使用
sys.argv
使用它。 This provides a list of arguments passed to the script, of which sys.argv[0]
is the script name (or "-c").这提供了传递给脚本的参数列表,其中
sys.argv[0]
是脚本名称(或“-c”)。 You can access the first argument with sys.argv[1]
although it's often better to do some error checking to make sure you actually get what you want.您可以使用
sys.argv[1]
访问第一个参数,尽管通常最好进行一些错误检查以确保您确实得到了您想要的。 I would often do something like:我经常会做这样的事情:
import sys
args = sys.argv
if args[1]:
password = args[1]
You can also use a more robust parser such as argparse .您还可以使用更强大的解析器,例如argparse 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.