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
1
  • 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]) Commented Dec 15, 2021 at 9:44

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

-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)

2 Comments

Nope this method is throwing me a EOFError.
The <<< feature in Bash is called a "here string". It is specific to Bash (though like most useful features, actually borrowed from ksh)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.