2012-02-18 128 views
1

我在練習13中學習Python的難題時遇到了額外的問題。
它希望我結合argv和raw_input,這是我無法弄清楚的。
任何人都可以幫我嗎?例子會很棒!
非常感謝!
編輯:下年度的原代碼是:學習Python的難題幫助:練習13

from sys import argv 

script, first, second, third = argv 

print "The script is called:", script 
print "Your first variable is:", first 
print "Your second variable is:", second 
print "Your third variable is:", third 
+1

如果你發佈了一些沒有坐在辦公桌上的本書的代碼,那就太好了。 – jdi 2012-02-18 02:25:08

+0

作爲參考,正在討論的練習在這裏:http://learnpythonthehardway.org/book/ex13.html – checkorbored 2012-02-18 02:25:21

回答

2

一個例子,就是答案,這是不太可能來幫助你的最佳方式沒有什麼區別。不過,也許你正在反思這個問題。我相信這個想法是使用一些命令行輸入(進入argv)和一些輸入的輸入(通過raw_input來創建)來創建一個報告這兩者的腳本。例如,它可能會產生:

The script is called: ex13.py 
Your first variable is: cheese 
Your second variable is: apples 
You entered the following data: foo bar baz 
+0

哦,這比我想要做的更有意義...謝謝! – 2012-02-18 02:28:45

0
import sys 

def main(): 
    all_args = sys.argv[:] 
    user = None 
    while user != 'STOP': 
     user = raw_input('You have %d args stored. Enter STOP or add another: ' % len(all_args)) 
     if user != 'STOP': 
      all_args.append(user) 
    print 'You entered %d args at the command line + %d args through raw_input: [%s]' % (len(sys.argv), len(all_args) - len(sys.argv), ', '.join(all_args)) 

if __name__ == '__main__': 
    main() 
0

這是令人困惑我也。作者將這個問題放在他的常見問題底部。

問:我不能將argv與raw_input()結合使用。 A:不要反套。只需在該腳本的最後使用raw_input()獲取某些內容然後將其打印出來即可。從此開始玩更多的方式來使用在同一個腳本。

+0

如果您有新問題,請通過單擊[提問](http://stackoverflow.com/questions/ask)按鈕來提問。如果有助於提供上下文,請包含此問題的鏈接。 – NKN 2014-10-28 20:07:53

+0

不是一個新問題。作者在例子下面的faq中回答了這個問題。我只是指出提交人已經有過這個問題並回答了。 – CM1980 2014-11-02 07:38:09

1

這是我想做到這一點:

from sys import argv 

script, weather, feeling = argv 

print "Hot or Cold", 
weather = raw_input() 

print "Happy or sad", 
feeling = raw_input() 

print "The name of the script is:" , script 
print "The day is:", weather 
print "Today I am feeling:", feeling 
0

這是我如何解決這個(注:你仍然必須提供的參數在最初運行腳本)

from sys import argv 

script, first, second, third = (argv) 

print "The script is called:", script 
print "Your first variable is:", first 
print "Your second variable is:", second 
print "Your third variable is:", third 

first = raw_input("\nNew First Variable? ") 
second = raw_input("New Second Variable? ") 
third = raw_input("New Last Variable? ") 

print "\n\nYour new variables are %s, %s, and %s" % (first, second, third) 

這裏是我得到的輸出:

C:\Users\mbowyer\Documents\Python_Work>python ex13a.py 1 2 3 


The script is called: ex13a.py 

Your first variable is: 1 

Your second variable is: 2 

Your third variable is: 3 

New First Variable? a 

New Second Variable? b 

New Last Variable? c 

Your new variables are a, b, and c 

C:\Users\mbowyer\Documents\Python_Work>