【问题标题】:output the command line called by asyncio subprocess?输出 asyncio 子进程调用的命令行?
【发布时间】:2021-06-27 08:28:58
【问题描述】:
扩展问题问here,
有没有办法找出创建 asyncio 子进程时传递的命令是什么?
示例代码:-
process = await asyncio.create_subprocess_shell(
command,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
print(process.arguments)
【问题讨论】:
标签:
python
python-3.x
asynchronous
subprocess
python-asyncio
【解决方案1】:
asyncio.subprocess.Process 不存储有关命令参数的任何信息。可以查看__dict__的班级。
实际上你知道命令行参数,因为你提供了它们。
如果您可以控制被调用程序的输出,我可以提供以下由main.py 和test.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)