跨平台Python代码

时间:2016-05-09 13:47:23

标签: python

修改

除了下面的其他信息之外,感谢一些有用的输入问题是由于使用strftime%s生成Unix时间戳(这是被查询的系统所需要的)。 Strftime%s与Windows平台不兼容,因此我需要使用另一种方法来生成Unix时间戳。 Jez已经提出了time.time(),我已经尝试过,但我显然没有在整个过程中的某个地方做到这一点。 我需要将这部分代码从使用strftime更改为time():

    if (args.startdate):
       from_time=str(int(args.startdate.strftime('%s')) * 1000)
    if (args.enddate):
       to_time=str(int(args.enddate.strftime('%s')) * 1000)

任何帮助或操纵者都非常感激。 :)

/修改

我已经获得了一个Python脚本,当它部署在Apple笔记本电脑上时似乎运行正常但在我在Windows机器上运行时会出现错误消息。我需要通过远程执行文件来讨论第三方,他只有一台Windows机器,所以我需要尝试找出它无法正常工作的原因。 我正在运行2.7以供参考。 此部分似乎是导致错误的位置:

if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('-s', "--startdate", help="The start date (included)- format YYYY-MM-DD -- if not specified then earliest available data", type=valid_date)
parser.add_argument('-e', "--enddate", help="The end date (excluded) - format YYYY-MM-DD  -- if not specified then 'now'", type=valid_date)
parser.add_argument('-u', "--user", help="User name to use", default='admin')
parser.add_argument('-p', "--password", help="Password for user", default='redwood')
parser.add_argument('-a', "--attribute", help="Attribute", choices=['temperature', 'motion', 'input-power', 'output-power'], default='motion')
parser.add_argument('host', help='Hostname/IP address of engine to connect to', default='127.0.0.1')
args = parser.parse_args()
    user = args.user    
    passwd = args.password
    if (args.startdate):
       from_time=str(int(args.startdate.strftime('%s')) * 1000)
    if (args.enddate):
       to_time=str(int(args.enddate.strftime('%s')) * 1000)

    scale=1
    unit='seconds since 1.1.1970'
    if (args.attribute == 'temperature'):
       path=temperature_path
       scale = 100
       unit = "Degrees Celsius"
    elif (args.attribute == 'output-power'):
       path=opower_path
       scale = 100
       unit = "Watts"
    elif (args.attribute == 'input-power'):
       path=ipower_path
       scale = 1000
       unit = "Watts"
    else:
       path=motion_path
    print "Epoch Time, Local Time (this machine), Attribute, Value (%s) " % unit
query_stats(args.host)

这是我用来执行的命令:

C:\Python27>python stats_query.py -s 2016-03-18 -e 2016-03-19 -u admin -p admin -a motion 192.168.2.222

这是我收到的错误消息:

Traceback (most recent call last):
File "stats_query.py", line 132, in <module>
from_time=str(int(args.startdate.strftime('%s')) * 1000)
ValueError: Invalid format string

如果有人有任何想法,我会非常感谢任何反馈。 抱歉,如果我问一个愚蠢的问题 - 我真的不太熟悉Python。

3 个答案:

答案 0 :(得分:1)

如果您想在几秒钟内打印 ,请使用%S(使用大写S)。

答案 1 :(得分:0)

(应该是评论)

正如其他人已经提到的那样,并非所有平台都提供所有指令。

Python的文档列出了跨平台的所有指令: https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior

答案 2 :(得分:0)

不确定您的函数中有哪些 valid_time ,但是如果您使用类似的内容:

def valid_time(t):
    format = "%Y-%m-%d"
    datetime.datetime.strptime(t, format)

它超越了您所描述的问题......之后,我看到其他问题,因为 motion_path 未定义。

更新:以下代码使用python 2.7在Windows7 Professional上运行(文件另存为 tryme.py

import argparse
import datetime

def motion_path():
  print "Got here.. no issues"

def query_stats(host):
  print "We'll query the host: %s" % host

def valid_time(t):
  format = "%Y-%m-%d"
  return datetime.datetime.strptime(t, format)

if __name__ == "__main__":
  parser = argparse.ArgumentParser()
  parser.add_argument('-s', "--startdate", help="The start date (included)- format YYYY-MM-DD -- if not specified then earliest available data", type=valid_time)
  parser.add_argument('-e', "--enddate", help="The end date (excluded) - format YYYY-MM-DD  -- if not specified then 'now'", type=valid_time)
  parser.add_argument('-u', "--user", help="User name to use", default='admin')
  parser.add_argument('-p', "--password", help="Password for user", default='redwood')
  parser.add_argument('-a', "--attribute", help="Attribute", choices=['temperature', 'motion', 'input-power', 'output-power'], default='motion')
  parser.add_argument('host', help='Hostname/IP address of engine to connect to', default='127.0.0.1')
  args = parser.parse_args()
  user = args.user  
  epoch = datetime.datetime.utcfromtimestamp(0)
  passwd = args.password
  if (args.startdate):
     from_time=str(int((args.startdate-epoch).total_seconds()))
  if (args.enddate):
     to_time=str(int((args.enddate-epoch).total_seconds()))

  print 'From: %s\nTo: %s\n' %(from_time, to_time)

  scale=1
  unit='seconds since 1.1.1970'
  if (args.attribute == 'temperature'):
     path=temperature_path
     scale = 100
     unit = "Degrees Celsius"
  elif (args.attribute == 'output-power'):
     path=opower_path
     scale = 100
     unit = "Watts"
  elif (args.attribute == 'input-power'):
     path=ipower_path
     scale = 1000
     unit = "Watts"
  else:
     path=motion_path
  print "Epoch Time, Local Time (this machine), Attribute, Value (%s) " % unit
  query_stats(args.host)

用于运行它的命令:

C:\Python27>python tryme.py -s 2016-03-18 -e 2016-03-19 -u admin -p admin -a motion 192.168.2.222

结果:

Epoch Time, Local Time (this machine), Attribute, Value (seconds since 1.1.1970)
We'll query the host: 192.168.2.222