subproccess.check_output 不识别 unix 命令

问题描述 投票:0回答:1
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)

尝试在 Linux 中运行此 python 脚本,但

subprocess
给出 127 错误(根据 this person here 称为 command not found)并添加换行符。

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'

我的路径是正确的,命令是存在的。我能做什么?

python subprocess
1个回答
0
投票

我不确定这是否是一个完整的答案,但部分问题是

readlines()
一直在尾随换行符。 你可以通过做删除它

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

for
循环内。

顺便说一句,如果

x
包含空格或其他有问题的字符,不使用
shell=True
可能更容易:

output = subprocess.check_output(['command', '-L', x.rstrip('\n'), '-N'], stderr=subprocess.STDOUT)
© www.soinside.com 2019 - 2024. All rights reserved.