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'
我的路径是正确的,命令是存在的。我能做什么?
readlines()
一直在尾随换行符。
你可以通过做删除它
x = x.rstrip('\n')
output = ...
在
for
循环内。
顺便说一句,如果
x
包含空格或其他有问题的字符,不使用shell=True
可能更容易:
output = subprocess.check_output(['command', '-L', x.rstrip('\n'), '-N'], stderr=subprocess.STDOUT)