英文:
Shell command excution on Python2.7
问题
以下是翻译好的部分:
想要验证网站域名是否包含“com”。假设我有一个shell变量如下:
export FIRST_URL="http://www.11111.com"
export SECOND_URL="http://www.22222.org"
用户使用部分shell变量作为参数调用Python脚本,如下:
python2.7 FIRST # 或者
python2.7 SECOND
Python脚本如下:
import sys, os, subprocess
PART_URL = sys.argv[1]
print("PART_URL=", PART_URL)
COMPLETE_URL = PART_URL+'_URL' # 形成完整的shell变量
cmd_str='echo {} | grep "com"'.format(COMPLETE_URL) # 等同于 echo $FIRST_URL | grep com
my_site=subprocess.check_output(cmd_str, shell=True) # 注意在Python 2.7中无法使用subprocess.run()
print("The validated Site is ", my_site)
输出应该是 "The validated Site is http://www.11111.com"
英文:
Want to verify if site domain contains "com". Assume I have shell varibale as
export FIRST_URL="http://www.11111.com"
export SECOND_URL="http://www.22222.org"
User calls Python script with parameter (partial shell varibale) as
python2.7 FIRST # OR
python2.7 SECOND
Python script is,
import sys, os, subprocess
PART_URL = sys.argv[1]
print( "PART_URL=",PART_URL)
COMPLETE_URL = PART_URL+'_URL' # Formed a full shell varibale
cmd_str='echo {} | grep \"com\".format(COMPLETE_URL)' # equivalent to echo $FIRST_URL | grep com
my_site=subprocess.check_output(cmd_str, shell=True) # Note we cant use subprocess.run() in Python Python 2.7
print("The validated Site is ", my_site)
The output should be "The validated Site is http://www.11111.com"
答案1
得分: 0
$ export FIRST_VAR="http://www.11111.com"
$ python
>>> foo = 'FIRST'
>>> print os.environ[foo + '_VAR']
http://www.11111.com
>>>
英文:
Refer https://stackoverflow.com/questions/4906977/how-to-access-environment-variable-values
$ export FIRST_VAR="http://www.11111.com"
$ python
>>> foo = 'FIRST'
>>> print os.environ[foo + '_VAR']
http://www.11111.com
>>>
答案2
得分: 0
已解决,
COMPLETE_URL = PART_URL + '_URL'
cmd_str = 'echo ${} | grep \'com\''.format(COMPLETE_URL)
my_site = subprocess.check_output(cmd_str, shell=True)
或者,我们可以使用:
my_site = subprocess.call(shlex.split(cmd_str))
英文:
Figured it out,
COMPLETE_URL = PART_URL+'_URL'
cmd_str='echo ${} | grep \'com\'.format(COMPLETE_URL)'
my_site=subprocess.check_output(cmd_str, shell=True)
Alteratively, we can use,
my_site=subprocess.call(shlex.split(cmd_str))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论