Subprocess kan soms complex zijn. Het probleem hier is de redirect (>) operator.
Dit werkt:
>>> import subprocess
>>> cmd = 'echo "test" > blaat.txt' # Geen split()
>>> subprocess.call(cmd, shell=True) # Uitvoeren in de shell
0
>>> import os; os.path.exists("blaat.txt")
True
Door de redirect operator moet het commando in de shell uitgevoerd worden waardoor het ook niet nodig is om het commando te splitsen.
The shell argument (which defaults to False) specifies whether to use the shell as the program to execute. If shell is True, it is recommended to pass args as a string rather than as a sequence.
Begrijp ik het goed dat alleen subprocess gebruikt kan worden? Alles kan natuurlijk ook met pure Python modules of zelfs redirects en pipes gebruiken met subprocess.
Uw voorbeeld:
>>> with open("blaat2.txt", "w") as outfile:
... subprocess.call('echo "test"', stdout=outfile, shell=True)
...
0
>>> import os; os.path.exists("blaat2.txt")
True
De documentatie zou normaal zo goed als alle mogelijkheden omvatten.