简体   繁体   English

使用pdsh通过linux解析内联python命令

[英]Parsing inline python command via linux using pdsh

So, I am trying to issue this command from a python script that collects cpu information across a predetermined number of nodes in a cluster. 因此,我试图从python脚本发出此命令,该脚本收集群集中预定数量节点上的cpu信息。 Here I use a fanout of 2 and only run it on nodes b127 through b129 for testing purposes. 在这里,我使用2的扇出,并且仅在节点b127到b129上运行它以进行测试。

    pdsh -f2 -w b[127-129] 'python -c "import multiprocessing
    num_cpu = multiprocessing.cpu_count()
    stat_fd = open('/proc/stat')
    stat_fd.close()"'

I printed the command and this is what it shows on the terminal. 我打印了命令,这就是终端上显示的内容。 Thus, telling me that the quotes and commands are properly formatted. 因此,告诉我引号和命令的格式正确。 I get this string by executing the following code: 我通过执行以下代码来获取此字符串:

    python_command = "'python -c "\
                 + "\"import multiprocessing\n"\
                 + "num_cpu = multiprocessing.cpu_count()\n"\
                 + "stat_fd = open(\'/proc/stat\')\n"\
                 + "stat_fd.close()\"'"

    command = "pdsh -f2 -w b[127-129] " + python_command
    print command

Unfortunately, the line with open(\\'/proc/stat\\') seems to be the problem as that is the only line that causes the parser to fail due to the nested single quotes. 不幸的是,带有open(\\'/ proc / stat \\')的行似乎是问题所在,因为这是导致解析器由于嵌套的单引号而失败的唯一行。 I've tried numerous combinations of quoting and escaping in order to make it work to no avail. 我尝试了多种引号和转义组合,以使其无效。 I've omitted some code between the opening and closing of the file to minimize the posted code. 为了省去发布的代码,我在文件的打开和关闭之间省略了一些代码。

I searched around and found this link , but found it was too simple of an example because I could replicate those commands. 我四处搜索并找到了此链接 ,但是发现它太简单了,因为我可以复制这些命令。 And yes, I know I can use bash commands to get what I want done and I may end up doing so, but this one has me beating my head on the wall. 是的,我知道我可以使用bash命令来完成我想做的事情,但我最终可能会这样做,但这使我无法自拔。 I also have scripts that gather data using top and ps so I don't need an explanation using them. 我也有使用top和ps收集数据的脚本,因此不需要使用它们的解释。 I greatly appreciate the help in advance. 我非常感谢提前提供的帮助。

Try this: 尝试这个:

python_command = """pdsh -f2 -w b[127-129] 'python -c "import multiprocessing
num_cpu = multiprocessing.cpu_count()
stat_fd = open(\\"/proc/stat\\")
stat_fd.close()"'"""

In Python, you can use triple quotes ( """...""" or '''...''' ) for strings containing new lines and single/double quotes. 在Python中,您可以对包含换行符和单/双引号的字符串使用三引号( """..."""'''...''' )。

The last level of quotes (on the open() line) will need to be escaped so that they don't conflict with outer quotes. 最后一级的引号(在open()行上)将需要转义,以免与外部引号冲突。 You also need to escape the backslashes so they aren't immediately consumed by Python when interpreting the string: \\\\" . 您还需要转义反斜杠,以便Python在解释字符串\\\\"时不会立即使用它们。

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

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