为什么我的 bash 执行的 python 脚本只将文件名输出到 txt 文件?

Why is my bash executed python script outputting just the filename to a txt file?

我有两个文件。 执行 python 文件的 bash。现在,我只是想通过简单地打印命令行参数来了解命令行参数如何为 python 工作。

我希望命令行参数是 bash 循环中的“i”...

do
    /usr/bin/time python3 file_name.py $i > ./run/file_output$i.txt
done

python 文件

import sys

def run():
     print(sys.argv[0])

if __name__ == "__main__":
     run()

输出的 txt 文件已创建并正确编号,但每个文件只有 filen_ame.py 而不是 i 的值。

谢谢。

那是因为 sys.argv[0] 是可执行文件的名称,而不是第一个参数,您将从以下程序中看到:

import sys
for arg in sys.argv:
    print(arg)

当 运行 时,您会看到:

pax> python3 prog.py a b c
prog.py
a
b
c

换句话说,如果你想要第一个参数,使用sys.argv[1]