Python equivalent to Bash $()
I search the Python equivalent for the following Bash code:
VAR=$(echo $VAR)
Pseudo Python code could be:
var 开发者_Go百科= print var
Can you help? :-)
Regards
Edit:
I search a way to do this:
for dhIP in open('dh-ips.txt', 'r'):
gi = GeoIP.new(GeoIP.GEOIP_MEMORY_CACHE)
print gi.country_code_by_addr(print dhIP) # <-- this line is my problem
In Bash i would do it like this:
print gi.country_code_by_addr($(dhIP)) # only pseudo code...
Hope it's more clear now.
Edit2:
Thank you all! Here's my solution which works. Thanks to Liquid_Fire for the remark with the newline char and thanks to hop for his code!
import GeoIP
fp = open('dh-ips.txt', 'r')
gi = GeoIP.new(GeoIP.GEOIP_MEMORY_CACHE)
try:
for dhIP in fp:
print gi.country_code_by_addr(dhIP.rstrip("\n"))
finally:
fp.close()
You don't need a print
in there, just use the name of the variable:
for dhIP in open('dh-ips.txt', 'r'):
gi = GeoIP.new(GeoIP.GEOIP_MEMORY_CACHE)
print gi.country_code_by_addr(dhIP)
Also note that iterating through a file object gives you lines with the newline characters at the end. You may want to use something like dhIP.rstrip("\n")
to remove them before passing it on to country_code_by_addr
.
Just use dhIP
as it is. There is no need to do anything special with it:
for dhIP in open('dh-ips.txt', 'r'):
gi = GeoIP.new(GeoIP.GEOIP_MEMORY_CACHE)
print gi.country_code_by_addr(dhIP)
NB: There are some other issues with your code.
Without being familiar with the library you use, it seems to me that you unnecessarily instantiate GeoIP in every iteration of the loop. Also, you should not throw away the file handle, so you can close the file afterwards.
fp = open('dh-ips.txt', 'r')
gi = GeoIP.new(GeoIP.GEOIP_MEMORY_CACHE)
try:
for dhIP in fp:
print gi.country_code_by_addr(dhIP)
finally:
fp.close()
Or, even better, in 2.5 and above you can use a context manager:
with open('dh-ips.txt', 'r') as fp:
gi = GeoIP.new(GeoIP.GEOIP_MEMORY_CACHE)
for dhIP in fp:
print gi.country_code_by_addr(dhIP)
You might want to try these functions:
str(var)
repr(var)
If you're just trying to reassign a value to the same name it would be:
var = var
Now if you're trying to assign the string representation (which is usually what print
returns) of whatever object is referred to by var
:
var = str(var)
Is that what you're after?
精彩评论