簡體   English   中英

相當於Bash $()的Python

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM