Python 相当于 Bash $()
我搜索以下 Bash 代码的 Python 等效项:
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 false code...
希望现在更清楚了。
编辑2:
谢谢大家!这是我的有效解决方案。感谢 Liquid_Fire 对换行符的评论,并感谢 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()
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()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您不需要在其中使用
print
,只需使用变量的名称即可:另请注意,迭代文件对象会在末尾提供带有换行符的行。您可能需要使用
dhIP.rstrip("\n")
之类的方法将其删除,然后再将其传递给country_code_by_addr
。You don't need a
print
in there, just use the name of the variable: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 tocountry_code_by_addr
.只需按原样使用
dhIP
即可。不需要对它做任何特殊的事情:注意:您的代码还存在一些其他问题。
如果不熟悉您使用的库,在我看来,您没有必要在循环的每次迭代中实例化 GeoIP。另外,您不应该丢弃文件句柄,以便之后可以关闭文件。
或者,更好的是,在 2.5 及更高版本中,您可以使用上下文管理器:
Just use
dhIP
as it is. There is no need to do anything special with it: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.
Or, even better, in 2.5 and above you can use a context manager:
您可能想尝试这些函数:
str(var)
repr(var)
You might want to try these functions:
str(var)
repr(var)
如果您只是尝试将一个值重新分配给同一个名称,则情况如下:
现在,如果您尝试分配所引用的任何对象的字符串表示形式(通常是
print
返回的内容) byvar
:这就是你想要的吗?
If you're just trying to reassign a value to the same name it would be:
Now if you're trying to assign the string representation (which is usually what
print
returns) of whatever object is referred to byvar
:Is that what you're after?