[英]How to read command line arguments for a Python script from a file without using a redirect?
I have a Python script that expects four command line arguments. 我有一个Python脚本,需要四个命令行参数。 Rather than typing out the values of these arguments in the command line every time I run the script, I want to store the values of the command line arguments in a file and have the Python script read those values from that file as command line arguments .
我不想每次运行脚本时都在命令行中输入这些参数的值,而是希望将命令行参数的值存储在文件中,并让Python脚本从该文件中将这些值作为命令行参数读取。 For instance, if my desired command line arguments are
例如,如果我想要的命令行参数是
0 1 2 3
then the contents of a file called arguments_in_here.txt
would be 0 1 2 3
. 那么一个名为
arguments_in_here.txt
的文件的内容将为0 1 2 3
。 I would like some invocation on the command line like 我想要在命令行上进行一些调用
$ python myscript.py < arguments_in_here.txt
to be interpreted as 被解释为
$ python myscript.py 0 1 2 3
I already know that just using <
doesn't work because I tried it out. 我已经知道仅使用
<
不起作用,因为我尝试了。
I can use xargs
in the following way 我可以通过以下方式使用
xargs
$ cat arguments_in_here.txt | xargs python myscript.py
and achieve the desired result, but sort of in the Pythonic spirit I am wondering if there is a more direct and concise way to achieve what I want, without having to use a redirect. 并达到预期的结果,但是我想知道是否存在一种更直接,更简洁的方法来实现我想要的结果,而不必使用重定向。
Note: I could modify my Python script to take a file name as a command line argument, store my desired command line argument values in there, and then have my script pull the values from the file given to it on the command line, but I am wondering if there is any way for the Python script to read the command line arguments from a file through the command line. 注意:我可以修改Python脚本以将文件名用作命令行参数,在其中存储所需的命令行参数值,然后让脚本从命令行中给定的文件中提取值,但是我我想知道Python脚本是否可以通过命令行从文件中读取命令行参数。
Also note: If it ends up being relevant, I use Python 2.7 and tcsh 另请注意:如果最终有用,我将使用Python 2.7和tcsh
$ python myscript.py `cat arguments_in_here.txt`
这些是反引号,而不是常规的单引号。
If you use python myscript.py < arguments_here.txt
than you need to read from stdin
. 如果使用
python myscript.py < arguments_here.txt
,则需要从stdin
读取。 Alternative you can use cat
to get the arguments. 或者,您可以使用
cat
来获取参数。
python myscript.py $(cat arguments_here.txt)
A short form for $(cat filename)
is $(< filename)
in bash. $(cat filename)
缩写形式是bash中的$(< filename)
。
inputs = list(sys.stdin) # Get all of stdin
inputs = inputs[0] # Get only the first line
inputs = inputs.split() # python myscript.py < 0123_arguments.txt => [0, 1, 2, 3]
My approach to this problem would be to use the argparse library in order to parse one command with the file name. 我解决此问题的方法是使用argparse库 ,以便使用文件名解析一个命令。 Something like:
就像是:
$ python program filepath
Then you can create a function that read the properties from your file and execute a function with those params 然后,您可以创建一个函数,该函数从文件中读取属性并使用这些参数执行函数
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.