I have a python (v2.7) script that needs to clear the contents of a file before writing to it (if it exists). I'm able to execute the 'same' command on the command line without issue, but I get a either a python or bash error when calling variations of this command from python. Don't know what I'm missing.
Ultimate question: How can I create an empty file (or clear, if it exists) using a system call from Python (v2.7)?
Bash (successfully creates empty or clears existing file)
$ > test.txt
$ ls -l test.txt
-rw-rw-r--+ 1 <owner> <group> 0 Feb 9 11:26 test.txt
Python (w/o `shell=True'; fails with error)
I get the following error without using shell=True: OSError: [Errno 2] No such file or directory. Another post suggests I shouldn't get this error if I pass all arguments as individual string parameters. Not sure why I get this error.
$ python
>>> import subprocess
>>> subprocess.call(['>', 'test.txt']) # Same result w/ single/double quotes
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/subprocess.py", line 172, in call
return Popen(*popenargs, **kwargs).wait()
File "/usr/lib/python2.7/subprocess.py", line 394, in __init__
errread, errwrite)
File "/usr/lib/python2.7/subprocess.py", line 1047, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
Python (w/ `shell=True'; fails with error)
I tried adding shell=True per suggestions from the other post (shouldn't be security risk since the command is static), but I get the following bash error: Syntax error: end of file unexpected. I thought it might need an ending ; (maybe because of how python makes the call?), so I tried two adding a ; argument with the same end result.
$ python
>>> import subprocess
>>> subprocess.call(['>', 'test.txt'], shell=True) # Same result w/ single/double quotes
test.txt: 1: test.txt: Syntax error: end of file unexpected
2
>>> import subprocess
>>> subprocess.call(['>', 'test.txt', ';'], shell=True) # Same result w/ single/double quotes
test.txt: 1: test.txt: Syntax error: end of file unexpected