【问题标题】:Redirection opeartors, < and >, in os.system(cmd)os.system(cmd) 中的重定向运算符 < 和 >
【发布时间】:2013-11-11 12:20:32
【问题描述】:

推荐使用 os.system 来执行 python 脚本中的命令。此外,据称重定向操作员在那里工作。例如herehere。我愿意

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 模块。
  • &gt; 重定向依赖于正在执行的shell; os.system() 将字符串传递给 shell 进程,如果该进程不支持 &gt;,则会出现错误。
  • @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


【解决方案1】:

错误不...正如 Martijn 评论的那样 - 不推荐 - 使用 subprocess,例如:

import subprocess

with open('myfile.txt', 'w') as fout:
    subprocess.check_call('ls', stdout=fout)

【讨论】:

    猜你喜欢
    • 2016-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-15
    • 1970-01-01
    • 2016-11-09
    • 1970-01-01
    相关资源
    最近更新 更多