无法从python脚本中获取时间

时间:2016-11-04 00:05:47

标签: python

我正在测试两个python脚本,sunset.py调用gettimes.py来获取两次但是我没有得到任何返回。我知道gettimes.py被调用,因为它打印时间但我无法从sunset.py打印它们 gettimes.py

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]))

我做错了什么?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

Python不会以您认为的方式通过引用传递参数(它不像C ++引用语义)。它更像是通过指针传递;你可以改变收到的对象的属性,但如果你完全重新分配名称,你就失去了指向原始对象的指针(并且本地名称不再与调用者有任何关系)。

当您在arg1中重新分配arg2sunset.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