2016-11-04 60 views
0

我正在測試兩個python腳本sunset.py,它調用gettimes.py獲得兩次,但我沒有返回任何結果。我知道gettimes.py被稱爲它打印的時間,但我不能從sunset.py gettimes.py打印出來無法從python腳本獲取時間

from gettimes import main 

arg1 = '' 
arg2 = '' 

main(arg1, arg2) 

print 'Hour on ', arg1 
print 'Hour off ', arg2 

sunset.py

import ephem # to get sunrise and sunset 
import datetime # import date and time modules 
import time 
import sys 

def main(arg1, arg2): 
    here = ephem.Observer() #determine position of observer 
    here.lat = 'xx.xx085057' 
    here.lon = '-x.xx781850' 
    here.elevation = 43 #meters 
    sun = ephem.Sun() #define sun as object 

    arg1 = here.next_rising(sun).datetime().strftime('%H:%M') 
    arg2 = here.next_setting(sun).datetime().strftime('%H:%M') 
    print arg1, arg2 

if __name__=='__main__': 
    sys.exit(main(sys.argv[1], sys.argv[2])) 

我在做什麼錯?

回答

1

Python不會按照您認爲的方式引用參數(它不像C++引用語義)。這更像是通過指針傳遞;你可以改變接收到的對象的屬性,但是如果你完全重新分配了這個名字,你就失去了指向原始對象的指針(並且本地名稱不再與調用者有任何關係)。

當您重新分配arg1arg2sunset.main時,會重新觸發本地名稱,但調用者變量未更改。這裏通常的解決辦法是隻返回新值,垃圾無法通過時,功能並不需要它:

def main(): 
    here = ephem.Observer() #determine position of observer 
    here.lat = 'xx.xx085057' 
    here.lon = '-x.xx781850' 
    here.elevation = 43 #meters 
    sun = ephem.Sun() #define sun as object 

    arg1 = here.next_rising(sun).datetime().strftime('%H:%M') 
    arg2 = here.next_setting(sun).datetime().strftime('%H:%M') 
    return arg1, arg2 

# I have no idea why you were passing argv stuff to main here, 
# since it's not used, but this is a not too terrible way of handling it: 
if __name__ == '__main__': 
    print(*main()) 

而且在發送方:

from gettimes import main 

arg1, arg2 = main() 

print 'Hour on ', arg1 
print 'Hour off ', arg2 
+0

謝謝你的回答,兩者都有效,但我也擺脫了這裏我不需要的幾行,而當涉及到代碼時更少 – tamus

2

字符串不可變。

試試:

import ephem # to get sunrise and sunset 
import datetime # import date and time modules 
import time 
import sys 

def main(): 
    here = ephem.Observer() #determine position of observer 
    here.lat = 'xx.xx085057' 
    here.lon = '-x.xx781850' 
    here.elevation = 43 #meters 
    sun = ephem.Sun() #define sun as object 

    arg1 = here.next_rising(sun).datetime().strftime('%H:%M') 
    arg2 = here.next_setting(sun).datetime().strftime('%H:%M') 

# print arg1, arg2 
    return (arg1, arg2) 

if __name__=='__main__': 
    sys.exit(main(sys.argv[1], sys.argv[2])) 

from gettimes import main 


arg1, arg2 = main() 

print 'Hour on ', arg1 
print 'Hour off ', arg2 
+0

我想你的意思是說「字符串不是_mutable_」或「字符串不可變」。正如所寫的,你說的與你的意思相反。即使如此,字符串的可變性在這裏並不相關;他們在'main'中反彈了本地名稱,因此可變或不可變,它們不再與調用者傳遞的內容相關。 – ShadowRanger

+0

感謝您的回答 – tamus

+0

我的錯誤。謝謝。 – andercruzbr