如何在Visual Studio代码中运行sys.argv?请分步说明[关闭]

问题描述 投票:-2回答:2

请在下面的代码中逐步说明。当我在Visual Studio中运行此代码时显示错误。

错误:

we are going to erase ['d:/2 WEB DEVELOPMENT/4 PYTHON/Learning/LPHW/lphw.py'].
if you dont want that, hit CTRL-C(^c).
if you do want that, hit RETURN.
?& C:/Users/herma/Anaconda3/python.exe "d:/2 WEB DEVELOPMENT/4 PYTHON/Learning/LPHW/lphw.py"
opening the file...
Traceback (most recent call last):
  File "d:/2 WEB DEVELOPMENT/4 PYTHON/Learning/LPHW/lphw.py", line 60, in <module>
    target = open(filename,'w')
TypeError: expected str, bytes or os.PathLike object, not list 

from sys import argv script,
filename = argv, argv 
print(f'we are going to erase {filename}.') 
print('if you dont want that, hit CTRL-C(^c).') 
print('if you do want that, hit RETURN.') 
input('?')
print('opening the file...') 
target = open(filename,'w')
print('truncating the file. goodbye') 
target.truncate() 
print('now i m going to ask u three lines') 
line1 = input('line 1: ') 
line2 = input('line 2: ') 
line3 = input('line 3: ') 
print('i m going to write these to the file.') 
target.write(line1) 
target.write('\n')
target.write(line2) 
target.write('\n') 
target.write(line3)   
target.write('\n') 
print('and finally, we close it.') 
target.close()
python visual-studio-code argv sys
2个回答
0
投票

argv始终是一个列表,因为您可以提供多个参数。要访问文件路径,如果文件路径是您在cli中提供的参数,则必须使用argv [0]。

from sys import argv
filename = argv[0]

0
投票
import sys
filename = sys.argv[1]
# the rest

sys.argv是包含程序参数的列表。

元素0包含脚本名称。

如果要解析参数,则应使用模块argparse

© www.soinside.com 2019 - 2024. All rights reserved.