Shell command execution on Python2.7

huangapple go评论63阅读模式
英文:

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))

huangapple
  • 本文由 发表于 2020年1月3日 14:09:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/59573944.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定