1

選択を使用してこのリストからランダムな URL を選択しようとしていますが、うまくいきません。これが私のコードです:

import urllib, urllib2, sys
num = sys.argv[1]
print 'Started'
phones = [
'http://1.1.1.6/index.htm,'
'http://1.1.1.5/index.htm,'
'http://1.1.1.4/index.htm,'
'http://1.1.1.3/index.htm,'
'http://1.1.1.2/index.htm,'
'http://1.1.1.1/index.htm'
]
from random import choice
data = urllib.urlencode({"NUMBER":num, "DIAL":"Dial", "active_line":1})
while 1:
    for phone in phones:

                         urllib2.urlopen(choice(phone),data) # make call
                         urllib2.urlopen(choice(phone)+"?dialeddel=0") # clear
logs

これは私が得るエラーです

File "p.py", line 21, in ?
    urllib2.urlopen(choice(phone),data) # make call
  File "/usr/lib64/python2.4/urllib2.py", line 130, in urlopen
    return _opener.open(url, data)
  File "/usr/lib64/python2.4/urllib2.py", line 350, in open
    protocol = req.get_type()
  File "/usr/lib64/python2.4/urllib2.py", line 233, in get_type
    raise ValueError, "unknown url type: %s" % self.__original
ValueError: unknown url type: 5

どんな助けでも大歓迎です。ありがとう!

4

2 に答える 2

4

コンマは文字列の中にあります。その結果、phones 変数は 1 つの大きな文字列のリストになります。ランダムな選択により、その文字列から 1 文字が得られます。これを次のように変更します。

phones = [
    'http://1.1.1.6/index.htm',
    'http://1.1.1.5/index.htm',
    'http://1.1.1.4/index.htm',
    'http://1.1.1.3/index.htm',
    'http://1.1.1.2/index.htm',
    'http://1.1.1.1/index.htm',
]

また、電話を繰り返し処理するのではなく、 を使用して電話を選択するだけrandom.choice(phones)です。

また、2 つの URL 呼び出しに別のランダムな電話を選択していますが、これはあなたが望んでいるものではないと思います。これは、リファクタリングされた完全なコードです。

import urllib, urllib2, sys, random

phones = [
    'http://1.1.1.6/index.htm',
    'http://1.1.1.5/index.htm',
    'http://1.1.1.4/index.htm',
    'http://1.1.1.3/index.htm',
    'http://1.1.1.2/index.htm',
    'http://1.1.1.1/index.htm',
]

num = sys.argv[1]
data = urllib.urlencode({"NUMBER": num, "DIAL": "Dial", "active_line": 1})
while 1:
    phone = random.choice(phones)
    urllib2.urlopen(phone, data) # make call
    urllib2.urlopen(phone + "?dialeddel=0") # clear logs
于 2013-02-03T01:01:15.343 に答える
0

ランダムなインデックスを取得しようとすることができます

import random
phones = [
'http://1.1.1.6/index.htm',
'http://1.1.1.5/index.htm',
'http://1.1.1.4/index.htm',
'http://1.1.1.3/index.htm',
'http://1.1.1.2/index.htm',
'http://1.1.1.1/index.htm',
]

index random.randrange(0, len(phones)-1)
phones[index]
于 2013-02-03T01:06:59.887 に答える