Reputation: 841
How do I append to a file without opening it using Linux echo command? I've tried all sort of possibilities but unable to achieve the result. I'm not sure what I'm missing.
Documentation said to type out the exact command when shell is set to 'True' (Yes with security risk). The echo command works when I type it in Linux terminal but not through subprocess. I don't see the "test.txt" with 'This is a test string.'
>>> string = 'This is a test string.'
>>> cmd = 'echo \"' + string + '\" >> test.txt'
>>> cmd
'echo "This is a test string." >> test.txt'
>>>
>>> subprocess.check_call (cmd, shell = True)
0
>>>
>>> subprocess.call (['echo', '\"', string, '\"', ' >> ', ' test.txt'])
0
>>>
Upvotes: 2
Views: 3535
Reputation: 24788
As discussed in this answer, when using, shell=True
, you should pass a string, not a list, as the first argument. Thus the correct code would be:
subprocess.call('echo "foo" >> bar.txt', shell=True)
Demonstration:
>>> import subprocess
>>> subprocess.call('echo "foo" >> /tmp/bar.txt', shell=True)
0
>>> open('/tmp/bar.txt').read()
'foo\n'
>>>
Upvotes: 2
Reputation: 1166
You're passing the redirector ">>" as an argument to echo, but it's not an argument, it's part of the shell. You'll need to run the shell with a string for the command. That string would be what's in your cmd variable. The immediate option that comes to mind is:
subprocess.call(["sh", "-c", cmd]);
Though I've rarely used the subprocess module, and that may not be the best way to get what you want.
Upvotes: -1