【问题标题】:Error in Python Script regarding str(sys.argv[1])Python 脚本中关于 str(sys.argv[1]) 的错误
【发布时间】:2016-08-07 10:01:07
【问题描述】:
import MySQLdb as mdb
import math
import sys 
from decimal import Decimal

conn=mdb.connect('localhost','root','','testdb')
c=conn.cursor()

user_id=str(sys.argv[1])
lati=str(sys.argv[2])
longi=str(sys.argv[3])
radius=int(str(sys.argv[4]))

#user_id=1
#lati='28.635308'
#longi='77.224960'
#radius=1.5

错误是:

Traceback (most recent call last):
  File "C:\Python27\recommend.py", line 9, in <module>
    user_id=str(sys.argv[1])
IndexError: list index out of range

但是,# 注释的虚拟值工作正常。解决此错误有什么帮助吗?

【问题讨论】:

  • 你是如何运行这个脚本的?
  • 我在我的 PHP 页面中使用 shell_exec() 命令调用它。 eroor 在 Python Idle Shell 中指示。
  • 我的意思是,你是否在调用中传递了 4 个参数?您调用的确切命令是什么?
  • &lt;?php error_reporting(E_ALL); ini_set('display_errors', '1'); $lat = $_POST['lt']; $lon = $_POST['ln']; $uid = $_POST['id']; $rad = $_POST['rd']; #$lat = "28.674558"; #$lon = "77.274202"; #$uid = "1"; #$rad = "1"; $outs = 'python C:\Python27\recommend.py ' . $uid . ' ' . $lat . ' ' . $lon . ' ' . $rad; $output = shell_exec($outs); echo $output; ?&gt;
  • 我认为这最后一条评论非常有用。您应该将其包含在原始问题中,以便 php 人也可以帮助您

标签: php python arguments parameter-passing


【解决方案1】:

检查错误的一种方法是打印出 sys.argv 列表并检查其中包含的元素数量。错误的输出是说 sys.argv 中只有一个元素(很可能是脚本本身 - 脚本名称 -)。很可能在运行脚本时不提供参数(必须提供 4 个参数)。

【讨论】:

  • &lt;?php error_reporting(E_ALL); ini_set('display_errors', '1'); $lat = $_POST['lt']; $lon = $_POST['ln']; $uid = $_POST['id']; $rad = $_POST['rd']; #$lat = "28.674558"; #$lon = "77.274202"; #$uid = "1"; #$rad = "1"; $outs = 'python C:\Python27\recommend.py ' . $uid . ' ' . $lat . ' ' . $lon . ' ' . $rad; $output = shell_exec($outs); echo $output; ?&gt; 我用四个参数调用了脚本这有什么错误吗?
  • 我对您的 Python 和 PHP 文件进行了一些实验,但我不确定,但 radius=int(str(sys.argv[4])) 行不兼容(因为字符串不能级联到 int 函数必须是浮点数)。你可以试试这个radius=float(str(sys.argv[4]))。我希望它能解决你的问题。
猜你喜欢
  • 2011-05-06
  • 2014-03-13
  • 2015-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-18
  • 1970-01-01
相关资源
最近更新 更多