问题
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