简体   繁体   English

跨平台Python代码

[英]Cross platform Python code

EDIT 编辑

Further to the other below info and thanks to some helpful input the issue is caused by using strftime %s to generate a Unix Timestamp (which is what the system being queried requires). 除了下面的其他信息外,并且由于提供了一些有用的输入,此问题是由于使用strftime%s生成Unix时间戳(这是正在查询的系统所需要的)引起的。 Strftime %s is not compatible with the Windows platform therefore I need to use an alternative method to generate the Unix Timestamp. Strftime%s与Windows平台不兼容,因此我需要使用另一种方法来生成Unix时间戳。 Jez has suggested time.time() which I have experimented with but I'm clearly not doing it right somewhere along the way. Jez建议了我已经尝试过的time.time(),但显然我没有在整个过程中的某处都做。 I need to change this section of code from using strftime to 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)

Any help or a steer greatly appreciated. 任何帮助或引导非常感谢。 :) :)

/EDIT /编辑

I've been given a Python script which appears to run ok when deployed on an Apple laptop but gives an error message when I run it on a Windows machine. 我得到了一个Python脚本,该脚本在Apple笔记本电脑上部署时似乎可以正常运行,但是在Windows计算机上运行时却显示错误消息。 I need to talk a 3rd party through executing the file remotely and he only has a windows machine so I need to try and figure out why it isn't working. 我需要通过远程执行文件与第三方交谈,他只有一台Windows计算机,因此我需要尝试弄清楚为什么它无法正常工作。 I'm running 2.7 for reference. 我正在运行2.7供参考。 This section appears to be where the error is being caused: 此部分似乎是导致错误的地方:

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)

This is the command I'm using to execute: 这是我用来执行的命令:

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

And this is the error message I get: 这是我收到的错误消息:

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

If anyone has any thoughts I'd greatly appreciate any feedback. 如果有人有任何想法,我将不胜感激任何反馈。 Apologies if I'm asking a stupid question - I'm really not very familiar with Python. 抱歉,如果我要问一个愚蠢的问题-我对Python真的不是很熟悉。

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

(Should maybe be a comment) (可能是评论)

As others have mentioned already, not all directives are available on all platforms. 正如其他人已经提到的那样,并非所有指令都可在所有平台上使用。

Python's documentation lists all directives which are cross-platform: https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior Python的文档列出了所有跨平台的指令: https : //docs.python.org/2/library/datetime.html#strftime-strptime-behavior

Not sure what valid_time is in your function, but if you use something like: 不确定函数中的有效时间是什么,但是如果使用类似以下内容的方法:

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

It gets past the issue you are describing... after that, I see other issues, since motion_path is not defined. 它超越了您正在描述的问题...之后,由于未定义motion_path ,因此我看到了其他问题。

UPDATE : The following code works running on Windows7 Professional using python 2.7 (file saved as tryme.py ) 更新 :以下代码在使用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)

The command used to run it: 用于运行它的命令:

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

The results: 结果:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM