[英]Open a Python file with command line arguments
NOTE : I don't know if this has been asked before, but I couldn't find what wording would be used for asking this question 注:我不知道这是否已经被问过,但我找不到会用什么措辞问这个问题
I am creating a python file, and inside it needs to have a name of a file. 我正在创建一个python文件,并且在其中需要有一个文件名。 What I want is when you put
python Compiler.py <Filename>
in the command line, it takes the filename and uses it in the python file. 我要的是当你把
python Compiler.py <Filename>
在命令行中,它需要的文件名,并用它在Python文件。
How would I go about doing this? 我将如何去做呢?
someVariable = sys.argv[1]
This will take the first element after the file name and store it in the variable. 这将采用文件名之后的第一个元素,并将其存储在变量中。
someOtherVariable = sys.argv[2]
will take the second element, and so forth. 将采用第二个元素,依此类推。
python Compiler.py firstArg secondArg NthArg
Note: You will need to import sys
to use the sys
module. 注意:您将需要
import sys
才能使用sys
模块。
Use sys.argv
to get the args that are passed to the script. 使用
sys.argv
获取传递给脚本的args。
import sys
open(sys.argv[1], 'w').write('hello world')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.