重複の可能性:
Pythonでのコマンドライン引数
Python3.2を使用しています。私がやりたいのは、基本的に次のようなテキストを.txtファイルにエクスポートするプログラムです。
[program name] "Hello World" /home/marcappuccino/Documents/Hello.txt
私は初心者ですが、2つの「」の間にあるものを変数に入れる方法がわかりません。入ってるsys.argv
?どんな助けでも大歓迎です!ありがとう。
はい、コマンドライン引数を保持するのはsys.argvです。あなたは次のようなものが欲しいでしょう:
string_to_insert = sys.argv[1]
file_to_put_string_in = sys.argv[2]
これにより、「Hello World」がに割り当てられstring_to_insert
、/ home / marcappuccino / Documents/Hello.txtがに割り当てられfile_to_put_string_in
ます。
「dostuff.py」という名前のスクリプトがあり、次のように呼び出すとします。
dostuff.py "Hello World 1" "Hello World 2" hello world three
最終的には次のようになります。
sys.argv[0] = dostuff.py (might be a full path, depending on the OS)
sys.argv[1] = Hello World 1
sys.argv[2] = Hello World 2
sys.argv[3] = hello
sys.argv[4] = world
sys.argv[5] = three
引用符で囲まれた引数は、単一の引数と見なされます。
私はあなたが必要だと私が信じていることを示すために簡単なプログラムを書き留めました。引用符をそのまま使用するには、入力にエスケープ文字を追加する必要があります。
import sys
for i in range(0, len(sys.argv)):
print sys.argv[i]
出力:
python testing.py a b c "abcd"
testing.py
a
b
c
abcd
python testing.py a b c \"abcd\"
testing.py
a
b
c
"abcd"