[英]Python equivalent to Bash $()
我在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中,我会这样做:
打印gi.country_code_by_addr($(dhIP))#仅伪代码...
希望现在更加清楚。
编辑2:
谢谢你们! 这是我的解决方案。 感谢Liquid_Fire用换行符char所做的评论,也感谢Hop提供了他的代码!
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()
您不需要在那里print
,只需使用变量的名称即可:
for dhIP in open('dh-ips.txt', 'r'):
gi = GeoIP.new(GeoIP.GEOIP_MEMORY_CACHE)
print gi.country_code_by_addr(dhIP)
还要注意,遍历文件对象使您的行末尾带有换行符。 在将其传递给country_code_by_addr
之前,您可能希望使用dhIP.rstrip("\\n")
东西将其删除。
dhIP
原样使用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)
您可能想尝试以下功能:
str(var)
repr(var)
如果您只是想将值重新分配为相同的名称,则为:
var = var
现在,如果您要分配var
所引用的任何对象的字符串表示形式(通常是print
返回的内容):
var = str(var)
那是你追求的吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.