1

我正在以艰难的方式阅读学习 python,在第 15 章我想使用 import argv 来分配变量和原始输入来获得用户输入。脚本是:

from sys import argv 

script, filename, = argv

txt = open(filename)

print " Here's your file %r :" % filename
print  txt.read()

print " I'll also ask you to type it again: "

file_again = raw_input ("> ")

txt_again = open (file_again)

print txt_again.read ()

运行此脚本后,我收到错误,解压缩的值太多。

文件“ex15.py”,第 3 行,在脚本中,文件名 = argv
值错误:要解压的值太多

4

4 回答 4

2

只是几个指针...

from sys import argv  

script, filename, = argv 

在这里,您导入 argv 以访问命令行参数,然后期望它包含 2 个参数 - 脚本 (arg 0) 和要打印的文件名 (arg1)。尽管尾随逗号在语法上不是不正确的,但它不是必需的,只是看起来有点奇怪。我通常将其留argv在内部sys而不是将其拉入当前名称空间,但这是一个品味问题 - 它并没有真正的区别。我可能还会进行一些错误处理:

import sys

try:
    script, filename = sys.argv
except ValueError as e:
    raise SystemExit('must supply single filename as argument')

txt = (filename) 

print " Here's your file %r :" % filename 
print  txt.read() 

这里txt = (name)所做的就是使 txt 具有文件名的值。我相信您想要制作txt一个文件对象,以便您可以.read()从中:

txt = open(filename)
print "Here's the file contents of:", filename
print txt.read()

print " I'll also ask you to type it again: "     
file_again = raw_input ("> ")     
txt_again = open (file_again)      
print txt.again.read ()

你已经得到了open()这里,但txt.again.read()应该是txt_again.read()其他你会得到一个AttributeError- 所以只要改变它就可以了。

或者,支持查找的文件对象,因此您可以只rewind使用文件(因为您已经将文件读到最后,没有什么可再读的了),方法是:

txt.seek(0)
print txt.read()
于 2012-10-06T09:00:23.813 回答
0

O.K. so I found my problem I was not calling my script correctly. For example my py script is ex15.py with that script it will read a text using rw input and argv variables. And the filename for that is ex15_sample. I call the script with python ex15.py ex15_sample, I was confused with my last exercise. Where I used the variables I set in argv to call the script. But all of the feed back was very help and I also applied.

于 2012-10-07T01:14:59.457 回答
0

你是如何运行脚本的?

当你说,

script, filename = argv

您期待argv. 第一个是脚本名,第二个是文件名。如果您尝试使用超过 2 个参数运行脚本,那么您将收到这样的错误

python myscript.py myfile.py somethingelse

如果你想再传递一个参数给脚本,那么你需要指定第三个变量来解压这个值。像这样的东西

script, filename, option = argv

此外,如果您粘贴完整的回溯,这将有所帮助

于 2012-10-06T07:08:11.327 回答
-1

有一个额外的逗号

script, filename, = argv

它应该是

script, filename = argv
于 2012-10-06T05:31:39.110 回答