Passing Command Line argument to Python script to be able to open a connection to a web server
I'm writing some shell scripts to check if I can manipulate information on a web server.
I use a bash shell script as a wrapper script to kick off multiple python scripts in sequential order The wrapper script takes the web server's host name and user name and password. and after performing some tasks, hand's it to the python scripts.
I have no problem getting the information passed to the python scripts
host% ./bash_script.sh host user passwd
Inside the wrapper script I do the following:
/usr/dir/python_script.py $1 $2 $3
print "Parameters: "
print "Host: ", sys.argv[1]
print "User: ", sys.argv[2]
print "Passwd: ", sys.argv[3]
The values are printed correctly Now, I try to pass the values to open a connection to the web server: (I successfully opened a connection to the web server using the literal host name)
f_handler = urlopen("https://sys.argv[1]/path/menu.php")
Trying the variable substitution format throws the following error:
HTTP Response Arguments: (gaierror(8, 'nodename nor servname provided, or not known'),)
I tried different variations,
'single_quotes'
"double_quotes"
http://%s/path/file.php % value
for the variable substitution but I always get the same error
I assume that the urlopen function does not convert the sub开发者_开发技巧stituted variable correctly.
Does anybody now a fix for this? Do I need to convert the host name variable first?
Roland
You need to quote the string when doing variable substitution:
http://%s/path/file.php % value # Does not work
"http://%s/path/file.php" % value # Works
'http://%s/path/file.php' % value # Also works
"""http://%s/path/file.php""" % value # Also works
Python does not do string interpolation the way that PHP does -- so there is no way to simply "embed" a variable in a string and have the variable be resolved to its value.
That is to say, in PHP, this works:
"http://$some_variable/path/to/file.php"
and this does not:
'http://$some_variable/path/to/file.php'
In Python, all strings behave like the single-quoted string in PHP.
This:
f_handler = urlopen("https://sys.argv[1]/path/menu.php")
Should be:
f_handler = urlopen("https://%s/path/menu.php"%(sys.argv[1]))
精彩评论