python - 如何在 Visual Studio Code 中运行需要外部数据的 Python 文件
问题描述
我想在 VSC 中运行一个 Python 文件,但该文件需要来自两个不同 .txt 文件的外部数据。
例如,如果我在 Python IDLE 中运行它,我会打开 Python 文件,选择 Run...Customized,然后输入 .txt 文件的路径(例如 data/xxxxx.txt data/yyyy.txt output.png) 然后运行它。
您能否指出是否有办法在 VSC 中以这种方式运行文件,或者请我参考我在哪里可以找到任何可以满足此特殊要求的支持文档?
这是发生异常的函数:
def main():
# Check usage
if len(sys.argv) not in [3, 4]:
sys.exit("Usage: python generate.py structure words [output]")
# Parse command-line arguments
structure = sys.argv[1]
words = sys.argv[2]
output = sys.argv[3] if len(sys.argv) == 4 else None
# Generate crossword
crossword = Crossword(structure, words)
creator = CrosswordCreator(crossword)
assignment = creator.solve()
# Print result
if assignment is None:
print("No solution.")
else:
creator.print(assignment)
if output:
creator.save(assignment, output)
这是 VSC 中的例外:
Exception has occurred: SystemExit
Usage: python myfile.py structure words [output]
File "/Users/#######/myfile.py", line 277, in main
sys.exit("Usage: python myfile.py structure words [output]")
File "/Users//#######/myfile.py", line 299, in <module>
main()
解决方案
似乎您想使用 VS Code 调试器运行您的 python 文件,但无法告诉它使用什么参数来启动您的程序。
导航到调试器选项卡(Ctrl / Cmd + Shift + D)并单击“创建launch.json文件”,在出现的提示中指定要将启动配置添加到python文件。
它应该创建并打开一个样板 json 文件。"configurations"
然后可以在您的第一个元素内添加一个"args"
带有数组内所有必要参数的键。
完整的 json 文件可能如下所示:
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Python: Current File",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal",
// this is what I added manually
"args": [
"a.txt",
"b.txt",
"out.png"
]
}
]
}
然后,当您打开 python 文件时,通过调试选项卡或右上角的绿色箭头启动它。
编辑:
通过频繁更改命令行参数,您可以告诉 VS Code提示您输入这些参数。请参阅以下 json。如果有什么不明白的,请告诉我。
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Python: Current File",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal",
"args": [
"${input:firstArg}",
"${input:secondArg}",
"out.png"
]
}
],
"inputs": [
{
"id": "firstArg",
"type": "promptString",
"default": "myDefault.txt",
"description": "First txt"
},
{
"id": "secondArg",
"type": "promptString",
"description": "Now your second txt"
}
]
}
推荐阅读
- c# - 在 HttpClient 中设置标头以授权 rest api
- c# - 如何在 Prism 中不打开 MainWindow 的情况下创建模块目录和 Reigster 类型
- python - Pandas:agg() 给我的“系列”对象是可变的,因此它们不能被散列
- android - 完成后获取多个网络请求的结果
- python - 有没有办法加快在 python 中处理大型 CSV 和数据帧?
- php - Office365 smtp 并不总是与 php 邮件程序一起使用
- node.js - Typescript 编译的 JS 可以工作,但 ts-node-dev 抛出编译错误
- python - General setter for a class using strings
- mysql - 验证另一个表中记录的记录数据
- python - 当 __hash__ 和 __eq__ 在没有参数的情况下不可调用时,Python 的 dict 如何将类型管理为键?