使用argv时出错

时间:2011-11-17 09:49:39

标签: python syntax-error argv

我正在使用Learn Python The Hard Way学习Python。这是非常好的和有效的,但有一次我遇到了崩溃。我在网上搜索但找不到答案。 这是我的问题:

其中一个练习告诉你这样做:

from sys import argv

script, filename = argv

然后继续做我理解的事情:

print "we are going to erase %r." % filename
print "if you don't want that, hit CTRL-C (^C)."
print "if you do want that, hit RETURN."

raw_input("?")

print "opening the file..." 
target = open(filename, 'w')

第一部分是什么意思?

P.S。我得到的错误是:

  

syntaxError行继续符后面的意外字符

3 个答案:

答案 0 :(得分:2)

script, filename = argv

这是unpacking the sequence argv。第一个元素进入script,第二个元素进入filename。一般来说,这可以通过任何迭代来完成,只要左侧的变量与右侧的可迭代项完全一样多。

你显示的代码似乎没问题,我不知道为什么你会在那里得到语法错误。

答案 1 :(得分:1)

Unexpected character after line continuation character表示您使用延续字符\将命令拆分为两行(请参阅this question),但在其后添加了一些字符(例如空格)。

但我在您的代码中看不到任何\ ...

答案 2 :(得分:1)

代码工作正常,将代码中的代码放在codefile.py中并将dummydata文件传递给它:

$ python codefile.py dummydatafile.txt 
 We're going to erase 'test1.txt'.
 If you don't want that, hit CTRL-C (^C).
 If you do want that, hit RETURN.
 ?
 Opening the file...
 Truncating the file. Goodbye!
 Now I'm going to ask you for three lines.
 line 1: 
 line 2: 
 line 3: 
 I'm going to write these to the file.
 And finally, we close it.
$

这应该可以解决您的问题

相关问题