简体   繁体   English

Python:在 Unix(Fedora)系统上运行带有 'ls' 子进程的脚本时,argparse '错误:无法识别的参数'

[英]Python: argparse 'error: unrecognized arguments' when running script with 'ls' subprocess on Unix (Fedora) system

I encountered error: unrecognized arguments when trying to run my Python script in Fedora's Terminal.尝试在 Fedora 的终端中运行我的 Python 脚本时遇到error: unrecognized arguments的 arguments。 (It worked fine in Windows Shell.) I stripped it to absolute barebone version but the same error still persists. (它在 Windows Shell 中运行良好。)我将其剥离为绝对准系统版本,但同样的错误仍然存在。

import subprocess
from argparse import ArgumentParser

def print_filenames(directory):
    try:
        ls_output = subprocess.run(["ls", "-a", directory], shell=True, capture_output=True, text=True)
        ls_output.check_returncode()
        ls_output_str = ls_output.stdout
        ls_output_list = ls_output_str[:-1].split("\n")
        list_of_files = []
        for file in ls_output_list:
            list_of_files(file)
        return list_of_files
    except subprocess.CalledProcessError:
        # Same process but with dir /b command (for Windows)
        pass

if __name__ == '__main__':
    parser = ArgumentParser(prefix_chars='-', usage='Some usage', description='Description')
    parser.add_argument('directory', metavar='directory', type=str, help='str, required: directory')
    args = parser.parse_args()
    input_directory = args.directory

    print(get_filenames(input_directory))

Running script in terminal with expected output:在带有预期 output 的终端中运行脚本:

$ python myscript.py ./this_folder/*.xml

['./this_folder/first_file.xml', './this_folder/second_file.xml', './this_folder/third_file.xml']

Actual output:实际 output:

$ python myscript.py ./this_folder/*.xml

usage: Some usage
myscript.py: error: unrecognized arguments: ./this_folder/first_file.xml ./this_folder/second_file.xml ./this_folder/third_file.xml

Any idea what might be causing the problem?知道可能导致问题的原因吗? Why does my subprocess output appears as 'unrecognized arguments'?为什么我的子进程 output 显示为“无法识别的参数”?

After some trial-and-error, I found out the solution to this.经过反复试验,我找到了解决方案。 Instead of running subprocess like this:而不是像这样运行子进程:

subprocess.run(["ls", "-a", directory], shell=True, capture_output=True, text=True)

I ran it like this (with entire command in an f-string):我像这样运行它(整个命令在一个 f 字符串中):

subprocess.run([f"ls a {directory}"], shell=True, capture_output=True, text=True)

and it does exactly what it is supposed to do.它确实做了它应该做的事情。

I don't have clear understanding of the problem so any help would be appreciated.我对这个问题没有清楚的理解,所以任何帮助都将不胜感激。 My guess is that without putting entire command into a single (f-)string, subprocess runs just ls and ignores directory stated behind it.我的猜测是,如果不将整个命令放入单个(f-)字符串中,子进程只会运行ls并忽略它后面声明的directory At least that's what it seems to do.至少它似乎是这样做的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM