2016-12-07 3 views
0

私はこのスクリプトをタプルの内容を取得し、forループを使用して取得しようとしています(私はコードをどこに置くべきか分かりません)。コマンド内のタプル。この例では、私はfindをコマンドとして使用しました。エグゼキュータがsp1またはsp2を使用するオプションによって、使用されるタプルの量が決まります。タプルをコマンドに挿入するために使用

import sys, subprocess, os, string 

cmd = '/bin/find ' 

tuple = ('apple', 'banana', 'cat', 'dog') 

sp1 = tuple[0:1] 
sp2 = tuple[2:3] 

def find(): 
    find_cmd = subprocess.Popen(cmd + " * -name {}".format(type)), 
           stdout=subprocess.PIPE, 
           stderr=subprocess.PIPE, shell=True) 
    output, err = find_cmd.communicate() 
    find = output 
    find_temp = [] 
    find_temp = string.split(find) 
    if find_temp[0] == ' ': 
     print("Found nothing") 
    else: 
     print("Found {}".format(find_temp)) 

type_input = input("Are you looking for fruit or animals? ") 
if type_input == "fruit": 
    type = sp1 
elif type_input == "animals": 
    type = sp2 
    print("syntax error") 
    exit() 

find() 
+2

def find(what, cmd=FIND): find_cmd = subprocess.Popen('{cmd} * -name {what}'.format(cmd=cmd, what=what), stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) output, err = find_cmd.communicate() find = output find_temp = [] find_temp = string.split(find) if find_temp[0] == ' ': print("Found nothing") else: print("Found {}".format(find_temp)) 

今、あなたは、変数、または何彼らが尋ねを使用できますキーワード(例えば、 'tuple')は、そのスコープ内のビルトインの名前を上書きするためです。 http://stackoverflow.com/a/2418007/1248974 – davedwards

+0

あなたの問題は何ですか? – martineau

答えて

0

近づいていますが、やっていることをやっていない、それはちょっとばかりです。あなたはもっとうまくいくかもしれない。

むしろ、この奇妙なタプルのスライスのことをやってよりも、単にそれらに本名与える:あなたが言及したあなたのコメントでは

find_params = { 
    'fruit': ['apple', 'banana'], 
    'animals': ['cat', 'dog'], 
} 

:また

を、あなたは辞書を使用することができ

私のタプルは少し大きく、両方の変数は同じ値のいくつかを使用しています... これは私は2つの別々のリストに同じ値の多くを入力することから。

あなたはまだ素敵なアプローチを取ることができます。あなただけのサブセットを必要とする

cheeses = ('Wensleydale', 'Edam', 'Cheddar', 'Gouda') 
spam = ('Spam with eggs', 'Spam on eggs', 'Spam') 
confectionaries = ('crunchy frog', 'spring surprise', 'cockroach cluster', 
        'anthrax ripple', 'cherry fondue') 
food = cheeses + spam + confectionaries 

場合でも、あなたはまだのような何かを行うことができます。

food = cheeses + spam[:2] + confectionaries[-1:] 

をあなたは、パラメータ(複数可)を取る必要がありますあなたのfindコマンドの代わりに。また、フォーマット文字列を連結して使用する必要もありません。ただ、すべてのもののためのフォーマット文字列を使用します。影は組み込み変数に名前を付けるときに注意してください、脇

type_input = input("Are you looking for fruit or animals? ") 
try: 
    find(find_params[type_input]) 
except KeyError: 
    sys.exit('Unknown parameter {!r}'.format(type_input)) 

# Or use the variables 
if type_input == "fruit": 
    find(fruit) 
elif type_input == "animals": 
    find(animals) 
else: 
    sys.exit('Unknown parameter {!r}'.format(type_input)) 
+0

ブリリアント!共有していただきありがとうございます。さて、私の問題をはっきりと説明できないのは私のせいですが、現実世界の問題では、私のタプルはもう少し大きく、両方の変数は同じ値を使用しています。たとえば、 'sp1 =タプル[0:10]'と 'sp2 =タプル[0:20]'のようになります。これは、同じ値の多くを2つの別々のリストに入力するのを防ぎます。 – Clarkus978

+0

私は 'sp1'や' sp2'よりも適切な名前を与えています。私はいくつかの例で私の質問を更新します。 –

+0

答えを更新していただきありがとうございます。これは本当に役立ちます。 – Clarkus978

関連する問題