首页 > 解决方案 > argv 不读取 < 或 > python

问题描述

我正在使用 Python3,我想通过argv获取<>。这是我的代码:

str_args = [ str(x) for x in argv[1:] ] #create sequence
cmd = ''
for i in argv[1:]: #create str
    cmd += i + ' '
path = 'cmd.txt'
file=open(path, "a")
file.write(cmd + '\n')
file.close()

在 for 循环中,我连接参数以创建 linux 终端命令并写入 .txt 文件。我在其他地方执行该命令。当我输入 < 或 >(大于或小于)时,它只会传递到 < 或 >。例子:

回声 12 > test.txt

它只是得到

回声 12

并且没有通过 > test.txt 我该怎么办?它适用于非 < 或 > 示例。例如,它很好地传递了这样的命令:

平 8.8.8.8 -c 2 -s 60

谢谢

标签: pythonargumentsparameter-passingcommand-line-argumentsargv

解决方案


和被 shell 特别处理><这与 python 无关,因为 shell 在你的代码被调用之前将它们剥离出来。没有引号,>将命令的输出发送到作为下一个参数给出的文件的方法。在您的情况下,脚本的 stdout 将被重定向到 file test.txt

要将它们作为字符串传递,您必须使用引号或转义字符:

# using quotes
python the_script.py echo 12 '>' test.txt

# using the escape character
python the_script.py echo 12 \> test.txt

注意:这不仅仅是你必须担心的><诸如此类的角色*和其他一些角色也需要受到保护。这些都在 bash 手册页(或您正在使用的任何 shell 的手册页)中提到。


推荐阅读