Thanks Cameron, that worked perfectly. So if I want to run a terminal
command like the following which I want to use to strip the parens from
an output file with a perl expression, is it a similar exercise of
opening the file stripping the parens and closing?
Yes and no.
First up, you’re better off doing this directly in Python anyway.
$ perl -p -i -e s/['()]//g /Users/sean/python/data/emps.dat <---- cmd line
Second. This uses the -i option, which does in-place editing of the
file.
1: Do you really need to do that?
2: If you’re doing in-place editing, is there any output? And the stdin=
thing will not work for in-place editing. (a) it opens the file read
only and (b) the perl command won’t be given the filename, so it
cannotrewrite the file.
Finally, the command above is where subprocess.run
shines. If you were
doing this as a shell command (which i think your line above is, you
need to quote the shell-special characters. By using the argument list
approach this is simpler:
subprocess.run([ 'perl', '-p', '-i', '-e', "s/['()]g" ], ......)
Notice using double quotes to avoid any need to escape the embedded
single quote.
input
(1621, ‘Mami’, ‘Nishi’)
Shouldn’t the perl above strip the single quotes as well? Also, it would
strip brackets inside the string, which may not be what you want.
You’re better off writing something more targetted, though the
targetting depends on how much you’re sure of in the line format.
with open('/Users/sean/python/data/emps.dat') as f:
for line in f:
line = line.strip().lstrip('(').rstrip(')')
print(line)
You can be more precise (and more verbose) if necessary. Notice there’s
no regexp gunk in the code above, too.
Cheers,
Cameron Simpson cs@cskk.id.au