1

I am trying to run a Python script which passes a location of a file as an input of a shell command which is then executed using subprocess:

path_of_file = 'path_of_file.txt'
command = 'python3 Execute.py <<< {}'.format(path_of_file)
subprocess.run(command, shell=True)

but executing this throws me the error

/bin/sh: 1: Syntax error: redirection unexpected
tripleee
  • 175,061
  • 34
  • 275
  • 318
KaV
  • 23
  • 5
  • In case it's not obvious, your code is passing the file name as standard input to the command. That's not clearly wrong, but somewhat unusual. Perhaps you actually meant to put the file name as a command-line argument? That's simply `subprocess.run(['python3', 'Execute.py', path_of_file])` – tripleee Dec 15 '21 at 09:44

2 Answers2

2

Unless you specify otherwise, subprocess with shell=True runs sh, not Bash. If you want to use Bash features, you have to say so explicitly.

path_of_file = 'path_of_file.txt'
command = 'python3 Execute.py <<< {}'.format(path_of_file)
subprocess.run(command, shell=True, executable='/bin/bash')

But of course, a much better fix is to avoid the Bashism, and actually the shell=True entirely.

from shlex import split as shplit

path_of_file = 'path_of_file.txt'
command = 'python3 Execute.py'
subprocess.run(command.shplit(), input=path_of_file, text=True)

Best practice would dictate that you should also add check=True to the subprocess keyword arguments to have Python raise an exception if the subprocess fails.

Better still, don't run Python as a subprocess of Python; instead, import Execute and take it from there.

Maybe see also

tripleee
  • 175,061
  • 34
  • 275
  • 318
-1

It just look like a typo, in bash to input a file you should use << or < and not <<<.

So the script should look like this :

path_of_file = 'path_of_file.txt'
command = 'python3 Execute.py << {}'.format(path_of_file)
subprocess.run(command, shell=True)
Xiidref
  • 1,456
  • 8
  • 20
  • Nope this method is throwing me a EOFError. – KaV Dec 15 '21 at 08:56
  • 1
    The `<<<` feature in Bash is called a "here string". It is specific to Bash (though like most useful features, actually borrowed from `ksh`) – tripleee Dec 15 '21 at 09:08