0
import subprocess


with open("file.txt", 'r') as fl:

    xs = fl.readlines()

    for x in xs:
        output = subprocess.check_output(f"command -L {x} -N", shell=True, stderr=subprocess.STDOUT)
        print(output)

Trying to run this python script in Linux but subprocess gives 127 error (dubbed as command not found according to this person here) and adds a new line character.

Traceback (most recent call last):
  File "/home/user/Documents/the_test/script/pythonstuff/script.py", line 9, in <module>
    output = subprocess.check_output(f"command -L {x} -N", stderr=subprocess.STDOUT)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/lib/python3.11/subprocess.py", line 466, in check_output
    return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/lib/python3.11/subprocess.py", line 548, in run
    with Popen(*popenargs, **kwargs) as process:
         ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/lib/python3.11/subprocess.py", line 1024, in __init__
    self._execute_child(args, executable, preexec_fn, close_fds,
  File "/usr/lib/python3.11/subprocess.py", line 1901, in _execute_child
    raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'command -L x \n -N'

My path is correct and the command exists. What can I do?

Jugert Mucoimaj
  • 339
  • 1
  • 2
  • 14
  • Its a bug in your code - you should pass an array, not a string .. Essentially now you are trying to call a single command `command -L {x} -N` which ofcourse fails and you get "No such file or directory" .. – rasjani Mar 27 '23 at 12:38

1 Answers1

0

I'm not sure if this is a complete answer, but part of the problem is that readlines() keeps trailing linebreaks. You can remove it by doing

x = x.rstrip('\n')
output = ...

inside the for-loop.

By the way, if x contains spaces or other problematic characters, it might be easier not to use shell=True:

output = subprocess.check_output(['command', '-L', x.rstrip('\n'), '-N'], stderr=subprocess.STDOUT)
jfschaefer
  • 293
  • 1
  • 8