• 締切済み

Pythonスクリプトが実行できない

 インターネット上で公開されているスクリプトなのですが、実行しようとするとエラーが出てしまいます。どうすれば正しく実行することができるのか、分かる方教えていただけると助かります。よろしくお願いします。  エラーメッセージはスクリプトの下に記載します。  ニコニコ動画にログインし、マイページに新規マイリストを作成して、任意の動画をマイリストに登録するスクリプトです。 #!/usr/bin/env python #coding: utf8 userid="ここにメールアドレスを入力" passwd="ここにパスワードを入力" import sys, re, cgi, urllib, urllib2, cookielib, xml.dom.minidom, time import simplejson as json def getToken(): html = urllib2.urlopen("http://www.nicovideo.jp/my/mylist").read() for line in html.splitlines(): mo = re.match(r'^\s*NicoAPI\.token = "(?P<token>[\d\w-]+)";\s*',line) if mo: token = mo.group('token') break assert token return token def mylist_create(name): cmdurl = "http://www.nicovideo.jp/api/mylistgroup/add" q = {} q['name'] = name.encode("utf8") q['description'] = "" q['public'] = 0 q['default_sort'] = 0 q['icon_id'] = 0 q['token'] = token cmdurl += "?" + urllib.urlencode(q) j = json.load( urllib2.urlopen(cmdurl), encoding='utf8') return j['id'] def addvideo_tomylist(mid,smids): for smid in smids: cmdurl = "http://www.nicovideo.jp/api/mylist/add" q = {} q['group_id'] = mid q['item_type'] = 0 q['item_id'] = smid q['description'] = u"" q['token'] = token cmdurl += "?" + urllib.urlencode(q) j = json.load( urllib2.urlopen(cmdurl), encoding='utf8') time.sleep(0.5) #ログイン opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookielib.CookieJar())) urllib2.install_opener(opener) urllib2.urlopen("https://secure.nicovideo.jp/secure/login", urllib.urlencode( {"mail":userid, "password":passwd}) ) #トークン取得 token = getToken() #マイリストの作成と動画の登録 mid = mylist_create(u"テストリスト") addvideo_tomylist(mid, ["sm9","sm1097445", "sm1715919" ] ) <エラーメッセージ> >>> #?^í?^°?^¤?^ó ... opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookielib.CookieJar())) >>> urllib2.install_opener(opener) >>> urllib2.urlopen("https://secure.nicovideo.jp/secure/login", ... urllib.urlencode( {"mail":userid, "password":passwd}) ) <addinfourl at 4311877104 whose fp = <socket._fileobject object at 0x101007758>> >>> #?^?^??^ü?^¯?^ó?^?^??^? ... token = getToken() Traceback (most recent call last): File "<stdin>", line 2, in <module> File "<stdin>", line 8, in getToken UnboundLocalError: local variable 'token' referenced before assignment >>> #?^?^??^¤?^ê?^¹?^?^??^???^??^?^??^???^?^??^Ի?^???^ٻ?^̲ ... mid = mylist_create(u"?^?^??^¹?^?^??^ê?^¹?^?^?") Traceback (most recent call last): File "<stdin>", line 2, in <module> File "<stdin>", line 9, in mylist_create NameError: global name 'token' is not defined >>> addvideo_tomylist(mid, ["sm9","sm1097445", "sm1715919" ] ) Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'mid' is not defined >>> <環境>imac, mac os x, ターミナルを使用

  • Mac
  • 回答数1
  • ありがとう数1

みんなの回答

  • kmee
  • ベストアンサー率55% (1857/3366)
回答No.1

http://okwave.jp/qa/q7004997.html 対話モードに直接貼り付けないで、スクリプトとして実行してください。 スクリプト全体を通して評価しなければならないものを個別に評価しているので ・スクリプト中、後に定義している変数を、関数内で使っている→関数定義の段階では変数が未定義なため、定義に失敗→定義してない(失敗した)関数を利用しようとしてエラー となっています。 たしかに、スクリプト自身もあまりよくないですけど。

myu0528myu
質問者

お礼

教えていただいたとおり実行したら、成功しました。 前の質問共々ご親切にお答えいただきありがとうございました!

関連するQ&A

  • Pythonでexport PYTHONSTARTTUPがエラーになる

    Pythonでexport PYTHONSTARTTUPがエラーになる OS:Windows7 Python2.6.6使用 http://d.hatena.ne.jp/kazu_pon/20100921/p1 ↑のサイトを参照してpythonのインタラクティブモードをカスタマイズしようとおもったのですが、 >>> export PYTHONSTARTUP = ~/.pythonstartup File "<stdin>", line 1 export PYTHONSTARTUP = ~/.pythonstartup ^ SyntaxError: invalid syntax というようにエラーが出てしまいます。 また、直接、環境変数PYTHONSTARTUPにC:\Users\name\.pythonstartup.py (nameにはちゃんと自分の名前が入ってます)といれても Traceback (most recent call last): File "C:\Users\teruo\.pythonstartup.py", line 12, in <module> histfile = os.path.join(os.environ['HOME'], '.pythonhistory') File "C:\Python26\lib\os.py", line 423, in __getitem__ return self.data[key.upper()] KeyError: 'HOME' というようなエラーが出てしまいます。どこがいけないのでしょうか?宜しければご教授ください。

  • Pythonのコンパイルの仕方が分かりません。。

    Pythonのコンパイルの仕方が分かりません。。 最近、Pythonをやり始めて、 スクリプト(hello.py)を作成したのですが、 実行ができません。 どうしたらよいのでしょうか。 どなたか回答お願いします。 あと[hello.py]の中身は print “Hello, world!” です。 command lineには Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> と表示されていて、 hello.py と打つと、 Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'hello' is not defined >>> 返ってきます。

  • pythonのimportについて

    phthonの質問です. 「みんなのpython」という本で勉強中なのですが,turtle をimportしようとすると Tkinterがうまくconfigureされていないと出ているようなエラーが出ているのですがいまいち解決法がわかりません.PATHの問題かとも思い,いろいろいじったのですが… ちなみに開発環境はVMWareでUbuntuで行っています. 実行結果は以下のような感じです. >>> from turtle import * Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/lib/python2.5/lib-tk/turtle.py", line 18, in <module> import Tkinter File "/usr/local/lib/python2.5/lib-tk/Tkinter.py", line 38, in <module> import _tkinter # If this fails your Python may not be configured for Tk ImportError: No module named _tkinter 以上よろしくお願い致します.

  • Django python

    pythonでdjangoのシステムについてお聞きしたいのですが・・ python0.95バージョンは管理画面からユーザーが追加できないため、manage.pyからshellでユーザ登録をすると教わり、試してみたのですが以下のようなネームエラーがでてしまい、ユーザ登録ができません。 どなたか御存じの方いらっしゃいましたら教えてください。。 >>> user = User.objects.create_user('hogehoge','hoge@ss.jp','456789') Traceback (most recent call last): File "<console>", line 1, in ? NameError: name 'User' is not defined 設定しなくてはいけないファイルがあるのでしょうか? よろしくお願いします。

  • PythonのAPI使用について

    PythonでAPIを用いて情報を取得する練習をしています。 ---------------------------------------------- import urllib2, sys import xml.etree.ElementTree as etree try: railcode = sys.argv[1] except: railcode = '11302' resp = urllib2.urlopen('http://www.ekidata.jp/api/l/%s.xml'%railcode).read() output = {} tree = etree.fromstring(resp) ---------------------------------------------- 山手線のデータを取得し、tree構造を作ろうとしています。 おそらく、treeの中に'ekidata'があり、'line'と'station'のそれぞれのデータが入っていると思うのですが、それぞれのデータをどうやって表示させるのかがわかりません。 ---------------------------------------------- for e in tree: print e print e.tag print e.text ---------------------------------------------- としてみたところ、 ---------------------------------------------- <Element 'line' at 0x10caa0790> line <Element 'station' at 0x10caa0a50> station <Element 'station' at 0x10caa0bd0> station <Element 'station' at 0x10caa0d50> station <Element 'station' at 0x10caa0ed0> station <Element 'station' at 0x10caa5090> station (続く) ---------------------------------------------- のようになり ---------------------------------------------- for e in tree[1]: print e print e.tag print e.text ---------------------------------------------- のようにtreeの一つを選択すると ---------------------------------------------- <Element 'station_cd' at 0x10a06ba90> station_cd 1130201 <Element 'station_g_cd' at 0x10a06bad0> station_g_cd 1130201 <Element 'station_name' at 0x10a06bb10> station_name 大崎 <Element 'lon' at 0x10a06bb50> lon 139.728439 <Element 'lat' at 0x10a06bb90> lat 35.619772 ---------------------------------------------- のようにそれぞれの情報がでてきます。 各treeに収納されているであろうそれぞれの駅のデータから、駅名だけを取り出したりしたいと考えています。 treeの構造がわかっていないことが大きいかもしれません。 何かヒントを与えていただければうれしいです。 よろしくお願いします

  • Pythonのバージョンアップについて

    CentOS5.5にはPython2.4がデフォルトで入っているのですが、Python2.6でスクリプトを作成する必要がありバージョンアップをしているのですが、dbusモジュールのインポートができず行き詰っております。 具体的には、Python2.4とdbus-pythonがインストールされている状態で、下記のURLを参考にyumでPython2.6をインストールしました。 環境としては「/usr/bin/phthon2.4」と「/usr/bin/phthon2.6」が出来た状態です。 libは「「/usr/lib/phthon2.4」と「/usr/lib/phthon2.6」です。 dbus-pythonのインストール先は「/usr/lib64/python2.4/site-packages/dbus」になります。 Python2.4を環境で下記のインポートは問題ありません。 >>>import dbus しかし、Python2.6環境で同じコマンドを実行すると下記のようなエラーになります。 >>> import dbus Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named dbus dbusの再インストールはリスクが高いと思い、モジュールのパスを通してみたところ下記のようなエラーになりました。 >>> import sys >>> sys.path.append('/usr/lib64/python2.4/site-packages') >>> import dbus Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib64/python2.4/site-packages/dbus/__init__.py", line 1, in <module> from _dbus import * File "/usr/lib64/python2.4/site-packages/dbus/_dbus.py", line 45, in <module> import dbus_bindings ImportError: /usr/lib64/python2.4/site-packages/dbus/dbus_bindings.so: undefined symbol: Py_InitModule4 rpmでモジュールインストール先の変更や、Python自体をソースからインストールなどしてみたのですが、全てうまく行かない状態です。 Pythonバージョンアップ前にインストールされているモジュールの使い方をご存知の方がおられましたら、宜しくお願いします。

  • pythonでtwitterAPIを使用としたときのGAE上でのエラー

    pythonでtwitterAPIを使用としたときのGAE上でのエラー <class 'urllib2.HTTPError'>: HTTP Error 401: Unauthorized GAE上にこの様なエラーが出てしまい。twitterbotに反映されません。 import urllib2は行っているのですが原因が分からず困っています。 よろしくお願いします # -*- coding: utf-8 -*- import twitter import random import os # from tenki import information from google.appengine.api import users from google.appengine.ext import webapp from google.appengine.ext.webapp import util from google.appengine.ext.webapp import template # twitter.Api.__init__ method for override. def twitter_api_init_gae(self, username=None, password=None, input_encoding=None, request_headers=None): import urllib2 from twitter import Api self._cache = None self._urllib = urllib2 self._cache_timeout = Api.DEFAULT_CACHE_TIMEOUT self._InitializeRequestHeaders(request_headers) self._InitializeUserAgent() self._InitializeDefaultParameters() self._input_encoding = input_encoding self.SetCredentials(username, password) # 天気用に追加 # from urllib2 import urlopen # from xml.dom.minidom import parseString # from xml.etree.ElementTree import * # information = [] # io = urlopen("http://www.google.com/ig/api?weather=Tokyo") # dom = ElementTree(file=io) # cond = dom.find("//current_conditions") # for name in ["condition","temp_c","humidity","wind_condition"]: # information.append(cond.find(name).get("data")) # overriding API __init__ twitter.Api.__init__ = twitter_api_init_gae list = [ u"ante" ,u"Do my best" ,u"piyopiyopiyo" ,u"piyopiyo" ,u"ponyo" ,u"piyo" ,u"my name is anteroom" # ,u"Today's weather is " + information[0] # ,u"Today's weather is " + information[1] # ,u"Today's weather is " + information[2] # ,u"Today's weather is " + information[3] ] post = random.choice(list) api = twitter.Api("hoge","hoge") api.PostUpdate(post)

  • Pythonを使ったwebアプリについて

    開発環境はUbuntu12.04 Python2.7を使用しています 初歩的な質問ですが、 webサーバを作るときに simpleserver.py --------------------------------- import SimpleHTTPServer SimpleHTTPServer.test() --------------------------------- index.html -------------------------------------- <html> <head> </head> <body> <h1>Hello! Python!</h1> </body> </html> -------------------------------------- この2つを同ディレクトリに置いて $ python simpleserver.py と入力したところ、下のようなトレースバックが表示されました ------------------------------------------------------------------------------------------ Traceback (most recent call last): File "simpleserver.py", line 2, in <module> SimpleHTTPServer.test() File "/usr/lib/python2.7/SimpleHTTPServer.py", line 216, in test BaseHTTPServer.test(HandlerClass, ServerClass) File "/usr/lib/python2.7/BaseHTTPServer.py", line 595, in test httpd = ServerClass(server_address, HandlerClass) File "/usr/lib/python2.7/SocketServer.py", line 408, in __init__ self.server_bind() File "/usr/lib/python2.7/BaseHTTPServer.py", line 108, in server_bind SocketServer.TCPServer.server_bind(self) File "/usr/lib/python2.7/SocketServer.py", line 419, in server_bind self.socket.bind(self.server_address) File "/usr/lib/python2.7/socket.py", line 224, in meth return getattr(self._sock,name)(*args) socket.error: [Errno 98] Address already in use ------------------------------------------------------------------------------------------ 解決方法が分からないので教えていただけませんか?

  • Python NameError: global name 'val' is not definedの対処法

    Pythonで書かれたスクリプトである wien2venus.py(http://www.nims.go.jp/cmsc/staff/arai/wien/wien2venus.py)を実行したところ以下のようなエラーメッセージがでました。 NameError: global name 'val' is not defined というエラーはどう対処したらよいのでしょうか。 「global name 'val'」は、普通の関数ではないのでしょうか。 とても困っています。どうか、頂けないでしょうか。 お願いします。 --------------------------------------------- $ wien2venus.py 50 50 50 mesh: 50 50 50 Traceback (most recent call last): File "/usr/local/VESTA-i686/wien2venus.py", line 176, in <module> lapw5 = Lapw5(head, complex) File "/usr/local/VESTA-i686/wien2venus.py", line 13, in __init__ if val: NameError: global name 'val' is not defined ---------------------------------------------

  • Python codeのcron実行

    QPKGでPythonをダウンロードした後、 http://stackoverflow.com/questions/4460262/running-a-python-script-with-cron を参考に、 (1)Python codeの先頭に[!/usr/bin/env python]を付け (2)chmod +xで実行可能にし、 (3)crontab -e にて1分毎に実行させるようにした のですが1分毎にファイルが作成されません。pythonのコードの保存場所でも間違っているのでしょうか? ※以下にあるpathのQNAPDriveはQnap NASで作成した仮想ドライブ(M:\)です。 (1)コード名[P20_time.py]。実行させると、ファイル名と保存内容が[2014-04-14T11-25-39]のようになり、M driveに保存されるプログラム。EclipseのPydevにて動作確認済み。 #!/usr/bin/env python import datetime D = datetime.datetime.today().strftime("%Y-%m-%dT%H-%M-%S") File_Path = "M:\\" + str(D) + '.txt' F = open(File_Path, 'w') F.write(str(D)) F.close() (2)chmod +xで実行可能にした後、ls -laでパーミッションを確認 -rwxrwxrwx 1 admin administ 209 Apr 13 14:25 P20_time.py* (3)[crontab -e]で編集後、[crontab -l]で表示した内容 01 * * * * /share/QNAPDrive/P20_time.py 作業環境:QNAP NAS TS-212、Windows 7 ―――――――――――――――――――――――――――――――― なお、QNAPのサポートセンターに上記のような質問をした所、 I tried to run your script commands manually in Python command line. But first line will fail: >>> import datetime Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named datetime Maybe you need to install the Python module for your script to work. とあり、プログラム自身がおかしいと指摘されました。ただ、Tera Termを使ってcommand lineで import datetime と入力しても問題なかったです。もうはっきし言ってお手上げです。どなたか御教授頂けるよう、よろしくおねがいします。