[英]Python 3.x call function with sys.argv[]
我有一个处理文件内容的函数,但是现在我将函数中的文件名硬编码为关键字参数:
def myFirstFunc(filename=open('myNotes.txt', 'r')):
pass
我称之为:
myFirstFunc()
我想将参数视为文件名并处理内容。
如何修改上述声明? 我试过这个:
filename=sys.argv[1] # or is it 0?
我怎么称呼它?
这样的事情:
#!/usr/bin/python3
import sys
def myFirstFunction():
return open(sys.argv[1], 'r')
openFile = myFirstFunction()
for line in openFile:
print (line.strip()) #remove '\n'? if not remove .strip()
#do other stuff
openFile.close() #don't forget to close open file
然后我会把它称为如下:
./readFile.py temp.txt
这将输出temp.txt的内容
sys.argv[0]
输出脚本的名称。 在这种情况下./readFile.py
更新我的答案
因为似乎其他人想要try
如何使用Python检查文件是否存在? 关于如何检查文件是否存在的问题是一个很好的问题。 关于使用哪种方法似乎存在分歧,但使用接受的版本将如下:
#!/usr/bin/python3
import sys
def myFirstFunction():
try:
inputFile = open(sys.argv[1], 'r')
return inputFile
except Exception as e:
print('Oh No! => %s' %e)
sys.exit(2) #Unix programs generally use 2 for
#command line syntax errors
# and 1 for all other kind of errors.
openFile = myFirstFunction()
for line in openFile:
print (line.strip())
#do other stuff
openFile.close()
这将输出以下内容:
$ ./readFile.py badFile
Oh No! => [Errno 2] No such file or directory: 'badFile'
你也许可以做到这一点用if
语句,但我喜欢这种在EAFP VS LBYL评论
对于Python 3,您可以使用上下文管理器。
# argv[0] is always the name of the program itself.
try:
filename = sys.argv[1]
except IndexError:
print "You must supply a file name."
sys.exit(2)
def do_something_with_file(filename):
with open(filename, "r") as fileobject:
for line in fileobject:
do_something_with(line)
do_something_with_file(filename)
这比你要求的要多,但这是我用来使用命令行参数的常用习惯用法:
def do_something_with_file(filename):
with open(filename, "r") as fileobject:
for line in fileobject:
pass # Replace with something useful with line.
def main(args):
'Execute command line options.'
try:
src_name = args[0]
except IndexError:
raise SystemExit('A filename is required.')
do_something_with_file(src_name)
# The following three lines of boilerplate are identical in all my command-line scripts.
if __name__ == '__main__':
import sys
main(sys.argv[1:]) # Execute 'main' with all the command line arguments (excluding sys.argv[0], the program name).
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.