質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

Q&A

2回答

7003閲覧

Python3.0 sysというモジュールが原因でエラーが出ます。

Surface-Yuki

総合スコア34

Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

0グッド

0クリップ

投稿2017/02/14 21:21

編集2017/02/14 21:41

環境
windows10
Python3.6
プログラミング初心者 Pythonを勉強初めて一週間です。

状況
コマンドプロンプトからintrocs-pythonというフォルダに入っている、useargument.pyというファイルを開く。
実行をすると以下のエラーが出ます。

Hi, Traceback (most recent call last): File "useargument.py", line 12, in <module> stdio.write(sys.argv[1]) IndexError: list index out of range

[質問点1]このエラーによると、12行目のstdio.write(sys.argv[1])に問題があるようなのですが、
どのように修正すれば良いのか教えてください。

そもそも、stdio.pyというファイルはあるのですが、sys.py
というファイルは見つかりません。
外部から入力するこれらのモジュールと呼ばれるデータの集まりはライブラリと言うそうですが、これらのファイルはpythonをダウンロード時に一緒にダウンロードされているという理解で正しいですか?

import sys となっているのに関わらず、sys.pyというファイルが見つからないのが不思議です。
全データ検索で探しましたが見つかりません。
sys.stdin.pyという名前の似ているファイルは見つかりました。

[質問点2]コード内の
stdio.write(sys.argv[1])

というのはどのような命令なのでしょうか?
import でstdioがすでに紐づけされているので、その中のwrite という命令を行っている
ということでしょうか?

イメージ説明

以下、useargument.py

#----------------------------------------------------------------------- # useargument.py #----------------------------------------------------------------------- import stdio import sys # Accept a name as a command-line argument. Write a message containing # that name to standard output. stdio.write('Hi, ') stdio.write(sys.argv[1]) stdio.writeln('. How are you?') #----------------------------------------------------------------------- # python useargument.py Alice # Hi, Alice. How are you? # python useargument.py Bob # Hi, Bob. How are you? # python useargument.py Carol # Hi, Carol. How are you?

以下、stdio.py

import sys import re #----------------------------------------------------------------------- # Change sys.stdin so it provides universal newline support. if (sys.hexversion < 0x03000000): import os sys.stdin = os.fdopen(sys.stdin.fileno(), 'rU', 0) else: sys.stdin = open(sys.stdin.fileno(), 'r', newline=None) #======================================================================= # Writing functions #======================================================================= def writeln(x=''): """ Write x and an end-of-line mark to standard output. """ if sys.hexversion < 0x03000000: x = unicode(x) x = x.encode('utf-8') else: x = str(x) sys.stdout.write(x) sys.stdout.write('\n') sys.stdout.flush() #----------------------------------------------------------------------- def write(x=''): """ Write x to standard output. """ if (sys.hexversion < 0x03000000): x = unicode(x) x = x.encode('utf-8') else: x = str(x) sys.stdout.write(x) sys.stdout.flush() #----------------------------------------------------------------------- def writef(fmt, *args): """ Write each element of args to standard output. Use the format specified by string fmt. """ x = fmt % args if sys.hexversion < 0x03000000: x = unicode(x) x = x.encode('utf-8') sys.stdout.write(x) sys.stdout.flush() _buffer = '' #----------------------------------------------------------------------- 省略 #----------------------------------------------------------------------- def isEmpty(): """ Return True if no non-whitespace characters remain in standard input. Otherwise return False. """ global _buffer while _buffer.strip() == '': line = sys.stdin.readline() if sys.hexversion < 0x03000000: line = line.decode('utf-8') if line == '': return True _buffer += line return False #----------------------------------------------------------------------- 省略 #----------------------------------------------------------------------- def readAllInts(): """ Read all remaining strings from standard input, convert each to an int, and return those ints in an array. Raise a ValueError if any of the strings cannot be converted to an int. """ strings = readAllStrings() ints = [] for s in strings: i = int(s) ints.append(i) return ints #----------------------------------------------------------------------- def readFloat(): """ Discard leading white space characters from standard input. Then read from standard input a sequence of characters comprising a float. Convert the sequence of characters to a float, and return the float. Raise an EOFError if no non-whitespace characters remain in standard input. Raise a ValueError if the next characters to be read from standard input cannot comprise a float. """ s = _readRegExp(r'[-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?') return float(s) #----------------------------------------------------------------------- def readAllFloats(): """ Read all remaining strings from standard input, convert each to a float, and return those floats in an array. Raise a ValueError if any of the strings cannot be converted to a float. """ strings = readAllStrings() floats = [] for s in strings: f = float(s) floats.append(f) return floats #----------------------------------------------------------------------- def readBool(): """ Discard leading white space characters from standard input. Then read from standard input a sequence of characters comprising a bool. Convert the sequence of characters to a bool, and return the bool. Raise an EOFError if no non-whitespace characters remain in standard input. Raise a ValueError if the next characters to be read from standard input cannot comprise a bool. These character sequences can comprise a bool: -- True -- False -- 1 (means true) -- 0 (means false) """ s = _readRegExp(r'(True)|(False)|1|0') if (s == 'True') or (s == '1'): return True return False #----------------------------------------------------------------------- def readAllBools(): """ Read all remaining strings from standard input, convert each to a bool, and return those bools in an array. Raise a ValueError if any of the strings cannot be converted to a bool. """ strings = readAllStrings() bools = [] for s in strings: b = bool(s) bools.append(b) return bools #----------------------------------------------------------------------- def readString(): """ Discard leading white space characters from standard input. Then read from standard input a sequence of characters comprising a string, and return the string. Raise an EOFError if no non-whitespace characters remain in standard input. """ s = _readRegExp(r'\S+') return s #----------------------------------------------------------------------- def readAllStrings(): """ Read all remaining strings from standard input, and return them in an array. """ strings = [] while not isEmpty(): s = readString() strings.append(s) return strings #----------------------------------------------------------------------- def hasNextLine(): """ Return True if standard input has a next line. Otherwise return False. """ global _buffer if _buffer != '': return True else: _buffer = sys.stdin.readline() if sys.hexversion < 0x03000000: _buffer = _buffer.decode('utf-8') if _buffer == '': return False return True #----------------------------------------------------------------------- def readLine(): """ Read and return as a string the next line of standard input. Raise an EOFError is there is no next line. """ global _buffer if not hasNextLine(): raise EOFError() s = _buffer _buffer = '' return s.rstrip('\n') #----------------------------------------------------------------------- def readAllLines(): """ Read all remaining lines from standard input, and return them as strings in an array. """ lines = [] while hasNextLine(): line = readLine() lines.append(line) return lines #----------------------------------------------------------------------- 省略 #======================================================================= # For Testing #======================================================================= def _testWrite(): writeln() writeln('string') writeln(123456) writeln(123.456) writeln(True) write() write('string') write(123456) write(123.456) write(True) writeln() writef('<%s> <%8d> <%14.8f>\n', 'string', 123456, 123.456) writef('formatstring\n') #----------------------------------------------------------------------- 省略

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答2

0

エラー原因についてはすでに回答あるとおりです。
ちなみにsys.argvとは「Python スクリプトに渡されたコマンドライン引数のリスト」です。

import sys となっているのに関わらず、sys.pyというファイルが見つからないのが不思議です。

これはsys.builtin_module_namesにヒントがあります。

コンパイル時に Python インタプリタに組み込まれた、すべてのモジュール名の入ったタプルです。

実際に以下を実行するとsysモジュールが含まれていることが分かります。

import sys print(sys.builtin_module_names)

つまりPython.exeにもともと含まれているため、sys.pyのようなモジュールファイルとしては存在しないと考えます。

投稿2017/02/15 06:38

can110

総合スコア38266

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

0

IndexError: list index out of rangeは配列の要素数以上の要素を参照しているときに起きるエラーです。
なので、argv[1]は存在しないということです。要素の数がいくつあるかを確認してみてください。

投稿2017/02/14 22:42

black_sleepman

総合スコア220

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

Surface-Yuki

2017/02/15 01:32

回答ありがとうございます。 argv[1]とはなんですか?何を指しているものでしょうか? sys.py ファイルが存在しない原因についてはわかりますか?
black_sleepman

2017/02/16 01:51

`import sys`は`sys.py`が存在しなくても使用することができます。 sys.pyを用いて何かをオーバーライドしているのであれば、存在していてもいいですが、 特に何もしていないのであれば、存在しなくても大丈夫だと思います。 `argv`とはファイルを実行するときにつけた引数が入るものです。 例えば、`test.py`を実行する際に`./test.py hoge fuga`とした場合、 `argv[0]: hoge` `argv[1]: fuga` というふうにデータが入ります。なので、起動時に引数を渡せるようになり、 その引数によって処理を変更できるということです。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだベストアンサーが選ばれていません

会員登録して回答してみよう

アカウントをお持ちの方は

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問