python - 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
谢谢
解决方案
和被 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 的手册页)中提到。
推荐阅读
- c# - Xaml 内部错误错误 WMC9999:在模块 CommonLanguageRuntimeLibrary 中找不到类型 System.MarshalByRefObject
- sql - 在 oracle 中显示来自两个不同函数的两条记录,而不是在一行中
- ios - Swift 获取和解析固定宽度的文本文件
- sql - DynamicsCRM 的 SQL 查询 每个帐户所有联系人的最新活动
- javascript - 如何在多个页面中查找匹配的文本
- sql - 检查表 1 中的日期是否大于表 2 中的日期。如果是,则在名为 Status 的新创建列中返回“Sent”
- c - 如何删除链表中的多个结构?
- json - WCF JSON序列化忽略DataMember.Name?
- python - 如何在快速排序程序中实现递归调用
- linux - 在连续/实时数据流上使用 grep