【发布时间】:2013-11-11 12:20:32
【问题描述】:
推荐使用 os.system 来执行 python 脚本中的命令。此外,据称重定向操作员在那里工作。例如here 和here。我愿意
os.system("ls > out.txt")
这确实适用于我的一台计算机。另一个产生
ls: cannot access >: No such file or directory
ls: cannot access out.txt: No such file or directory
我对另一个有访问权限的人有点限制,可以调查哪个进程产生此消息。但是os.system("ls") 列出了像魅力一样的文件。两者都是 Windows 7 机器。
【问题讨论】:
-
推荐使用os.system。不,实际上,它不是。您应该改用
subprocess模块。 -
>重定向依赖于正在执行的shell;os.system()将字符串传递给 shell 进程,如果该进程不支持>,则会出现错误。 -
@thefourtheye:
os.system()是低级别的,一个等待发生的安全漏洞(一旦你将不受信任的数据混入 shell 调用 shell 漏洞只是一个转义字符)。subprocess为您提供更大的灵活性,让您完全避免使用 shell。 -
@Val 即使这样,Martijn Pieters 也不喜欢它。所以,这背后会有一个很好的理由:)
-
引用
os.system()的文档:“subprocess模块为生成新进程和检索其结果提供了更强大的工具;使用该模块比使用此功能更可取。 请参阅subprocess文档中的Replacing Older Functions with the subprocess Module 部分,了解一些有用的食谱。”
标签: python shell jython io-redirection