简体   繁体   English

将命令行参数转发到Python中的进程

[英]Forwarding command line arguments to a process in Python

I'm using a crude IDE (Microchip MPLAB) with C30 toolchain on Windows XP. 我在Windows XP上使用带有C30工具链的原始IDE(Microchip MPLAB)。 The C compiler has a very noisy output that I'm unable to control, and it's very hard to spot actual warnings and errors in output window. C编译器有一个我无法控制的非常嘈杂的输出,并且很难在输出窗口中发现实际的警告和错误。

I want to write a python script that would receive arguments for compiler, call the compiler with same arguments, filter results and output them to stdout . 我想编写一个Python脚本,该脚本将接收编译器的参数,使用相同的参数调用编译器,过滤结果并将其输出到stdout Then I can replace the compiler executable with my script in toolchain settings. 然后,我可以在工具链设置中用脚本替换编译器可执行文件。 The IDE calls my script and receives filtered compiler output. IDE调用我的脚本,并接收过滤后的编译器输出。

My code for executing the compiler looks like this: 我执行编译器的代码如下所示:

arguments = ' '.join(sys.argv[1:])
cmd = '%s %s' % (compiler_path, arguments)
process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

The problem is that quotes from arguments are consumed on script execution, so if IDE calls my script with following arguments: 问题在于参数的引号会在脚本执行时使用,因此如果IDE使用以下参数调用我的脚本:

main.c -o"main.o" main.c -o“ main.o”

the value of arguments is 参数的值是

main.c -omain.o main.c -omain.o

The most obvious solution is to put whole argument list in quotes, but this would require modification in compiler calling code in IDE. 最明显的解决方案是将整个参数列表放在引号中,但这将需要在IDE中的编译器调用代码中进行修改。 I also tried using batch file, but it can only accept nine parameters (%1 to %9), and compiler is called with 15+ parameters. 我也尝试使用批处理文件,但是它只能接受9个参数(%1到%9),并且使用15个以上的参数调用编译器。

Is there a way to forward exactly the same arguments to a process from script? 有没有办法将完全相同的参数从脚本转发到进程?

Give the command arguments to Popen as a list: 将命令参数作为列表提供给Popen:

arguments = sys.argv[1:]
cmd = [compiler_path] + arguments
process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

As ChristopheD said the shell removes the quotes. 正如ChristopheD所说,外壳删除了引号。

But you don't need to create the string yourself when using Popen: it can handle that for you automatically. 但是使用Popen时不需要自己创建字符串:它可以自动为您处理。 You can do this instead: 您可以改为:

import sys, subprocess
process = subprocess.Popen(sys.argv[1:], executable=compiler_path, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

The subprocess module hopefully will pass the arguments correctly for you. 子流程模块有望为您正确传递参数。

您的shell正在吃引号(python脚本甚至都不会收到引号),因此我想让它们“不变”并不容易。

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

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