输出 asyncio 子进程调用的命令行?

output the command line called by asyncio subprocess?

扩展问题here, 有没有办法找出创建异步子进程时传递的命令是什么?

示例代码:-

process = await asyncio.create_subprocess_shell(
                    command,
                    stdout=asyncio.subprocess.PIPE,
                    stderr=asyncio.subprocess.PIPE,
                )
print(process.arguments)

asyncio.subprocess.Process 不存储有关命令参数的任何信息。您可以查看 class 的 __dict__

实际上你知道命令行参数,因为你提供了它们。

如果您可以控制被调用程序的输出,我可以提供以下由 main.pytest.py 组成的解决方法。 test.py 发回它从 main.py 收到的参数列表。

main.py 文件:

import asyncio


async def a_main():
    command_args = "test.py -n 1 -d 2 -s 3"  # your command args string
    process = await asyncio.create_subprocess_exec(
        "python",
        *command_args.split(),  # prepare args
        stdout=asyncio.subprocess.PIPE,
        stderr=asyncio.subprocess.PIPE,
    )
    print(type(process)) # asyncio.subprocess.Process
    # class instance do not store any information about command_args
    print(process.__dict__)
    stdout, stderr = await process.communicate()
    print(stdout)  # args are returned by our test script

if __name__ == '__main__':
    asyncio.run(a_main())

test.py 文件:

import sys

if __name__ == '__main__':
    print(sys.argv)