Redirection opeartors, < and >, in os.system(cmd)

寵の児 提交于 2019-12-08 10:12:21

问题


It is recommended that os.system is used for executing commands from python scripts. Furthermore, it is claimed that redirection operator work in there. For instance here and here. I do

os.system("ls > out.txt")

This works indeed on one of my computers. Another produces

ls: cannot access >: No such file or directory
ls: cannot access out.txt: No such file or directory

I am a bit limited on the other with access right to investigate which process produces this message. But os.system("ls") lists the files like charm. Both are Windows 7 machines.


回答1:


Err no... as Martijn commented - it's not recommended - use subprocess, e.g.:

import subprocess

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


来源:https://stackoverflow.com/questions/19906224/redirection-opeartors-and-in-os-systemcmd

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!