我在Python等价物中搜索以下Bash代码:
VAR=$(echo $VAR)
伪Python代码可能是:
var = print var
你能帮忙吗? : - )
此致
编辑:
我搜索的方法是这样做的:
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
在Bash我会这样做:
print gi.country_code_by_addr($(dhIP))#only pseudo code ...
希望现在更清楚了。
Edit2:
谢谢大家!这是我的解决方案。感谢Liquid_Fire对newline char的评论,感谢他的代码跳跃!
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()
答案 0 :(得分:3)
您不需要print
,只需使用变量的名称:
for dhIP in open('dh-ips.txt', 'r'):
gi = GeoIP.new(GeoIP.GEOIP_MEMORY_CACHE)
print gi.country_code_by_addr(dhIP)
另请注意,遍历文件对象会为您提供最后添加换行符的行。您可能希望使用dhIP.rstrip("\n")
之类的内容将其删除,然后再将其传递给country_code_by_addr
。
答案 1 :(得分:2)
按原样使用dhIP
。没有必要对它做任何特别的事情:
for dhIP in open('dh-ips.txt', 'r'):
gi = GeoIP.new(GeoIP.GEOIP_MEMORY_CACHE)
print gi.country_code_by_addr(dhIP)
注意:您的代码还存在其他一些问题。
在不熟悉您使用的库的情况下,在我看来,您在循环的每次迭代中都不必要地实例化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)
finally:
fp.close()
或者,更好的是,在2.5及以上版本中,您可以使用上下文管理器:
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)
答案 2 :(得分:1)
您可能想尝试这些功能:
STR(VAR)
再版(VAR)
答案 3 :(得分:0)
如果您只是尝试将值重新分配给同一个名称,那么它将是:
var = var
现在,如果您正在尝试为print
引用的任何对象分配字符串表示形式(通常是var
返回的内容):
var = str(var)
这就是你要追求的吗?