KaV
KaV

Reputation: 23

Python subprocess throws syntax error: redirection unexpected

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

Upvotes: 1

Views: 1125

Answers (2)

tripleee
tripleee

Reputation: 189317

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

Upvotes: 3

Xiidref
Xiidref

Reputation: 1529

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)

Upvotes: -1

Related Questions