I have added a bash command to my Python script – this bash command is used to linearise an input file (i.e. take a file with many lines, and merge it into one line). It works when I manually write the name of the file for the command (in this example, the input file is called input.txt):
import subprocess holder = subprocess.Popen('perl -ne "chomp;print;" input.txt', shell=True, stdout=subprocess.PIPE).stdout.read() print(holder)
However, I would like this bash command to take the name of the file specified by the user in the command line, and linearise it.
I have already tried to achieve this using %s
:
import subprocess import sys import os path = sys.argv[1] file = open(path, 'r') inp = file.read() holder = subprocess.Popen('perl -ne "chomp;print;" %s' % inp, shell=True, stdout=subprocess.PIPE).stdout.read() print(holder)
However, when I try this, the shell freezes and shows no output, and the bash $
prompt does not show, there is no error message.
I would like to know if there is a valid way to add a user input in this case and would appreciate any help.
EDIT: just to clarify, here is what I type into my shell to run the program with the second example:
$ python3 program.py input.txt
Advertisement
Answer
Why not just directly feed the input path to your subprocess, like this? I’m slightly confused as to why you would like to use perl within python do this however..
import subprocess import sys import os path = sys.argv[1] holder = subprocess.Popen('perl -ne "chomp;print;" %s' % path, shell=True, stdout=subprocess.PIPE).stdout.read() print(holder)
with this example input:
test.txt i i i i i
the program will output:
python linearize.py test.txt b'iiiii'