Search code examples
pythonequivalent

Python equivalent to Bash $()


I search the Python equivalent for the following Bash code:

VAR=$(echo $VAR)

Pseudo Python code could be:

var = 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()

Solution

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