如何处理管道中的撇号



我使用pipes.quote()函数来格式化我的命令/路径当命令/路径中有撇号时,该函数将把一个字符串分解为多个字符串。

例如,我的命令/字符串是

"cat 'test's dir/test's file.txt'"

pipes.quote()将其转化为

'cat '"'"'test'"'"''"'"''"'"'s dir/test'"'"''"'"''"'"'s file.txt'"'"''

我如何以一种通用的方式框架字符串,以便它处理这种情况,我可以使用转换后的字符串/命令在linux机器上运行?

您应该使用shlex.quote(),而不是过时的pipes.quote()

你需要给它一个没有引号的字符串。所以

filename = "test's dir/test's file.txt"
command = f"cat {shlex.quote(filename)}"
os.system(command)

但是,您可以通过使用subprocess模块而不是os.system()来完全避免这种需要。

filename = "test's dir/test's file.txt"
subprocess.run(["cat", filename]);

不使用shell来执行命令,所以不需要引号。

最新更新