我在
test's file.txt
目录中有一个名为 test's dir
的文件。
所以文件路径变成了test's dir/test's file.txt
。
我想捕获文件的内容,但由于该文件包含撇号和空格,因此我很难实现这一点。
我尝试了几个命令,包括
sh -c "cat 'test's dir/test's file.txt'"
sh -c 'cat "test's dir/test's file.txt"'
sh -c "cat '"'"'test's dir/test's file.txt'"'"'"
sh -c 'cat "test\'s\ dir/test\'s\ file.txt"'
还有很多 ...
但它们都不起作用。请您尝试一下:
sh -c "cat 'test'\''s dir/test'\''s file.txt'"
至于路径名部分,它是串联的:
'test'
\'
's dir/test'
\'
's file.txt'
如果你想执行
python
中的shell命令,请尝试:
#!/usr/bin/python3
import subprocess
path="test's dir/test's file.txt"
subprocess.run(['cat', path])
或立即:
subprocess.run(['cat', "test's dir/test's file.txt"])
由于
subprocess.run()
函数将命令作为列表,
不是单个字符串(可以使用 shell=True
选项),我们没有
担心命令周围的额外引用。
请注意
subprocess.run()
由 Python 3.5 或更高版本支持。
您可以使用此处-doc:
sh -s <<-'EOF'
cat "test's dir/test's file.txt"
EOF
此选项避免了两级引用的需要:
sh -c 'cat -- "$0"' "test's dir/test's file.txt"
请参阅如何通过“bash -c”命令使用位置参数?。 (这也适用于
sh -c
。)