[英]python - using backslash with subprocess.check_output
I am writing a script to connect to my wifi using Python in Ubuntu Operating System. 我正在编写一个脚本,以在Ubuntu操作系统中使用Python连接到我的wifi。 The follwing is my code: 以下是我的代码:
from subprocess import check_output
network = 'abcnetwork'
password = r'Pass|\|ew2017;'
output = check_output(
['nmcli d wifi connect {network} password {password}'.format(
network=network, password=password)],
shell=True
)
But I am getting the error because of \\
: 但是由于\\
:我遇到了错误:
/bin/sh: 1: |ew2017: not found
`enter code here`Traceback (most recent call last):
File "<stdin>", line 4, in <module>
File "/usr/lib/python3.5/subprocess.py", line 626, in check_output
**kwargs).stdout
File "/usr/lib/python3.5/subprocess.py", line 708, in run
output=stdout, stderr=stderr)
subprocess.CalledProcessError: Command '['nmcli d wifi connect abcnetwork password Pass|\\|ew2017;']' returned non-zero exit status 127
What is the mistake in my code. 我的代码有什么错误? Kindly help. 请帮助。
将命令作为单词列表而不是单个字符串(使用shell=False
,这是默认值)传递。
output = check_output(['nmcli', 'd', 'wifi', 'connect', network, 'password', password])
Don't use shell=True
to rely on the shell word splitting. 不要使用shell=True
依赖于shell单词拆分。 Instead, pass a list of arguments to check_output
: 相反,将参数列表传递给check_output
:
output = check_output([
'nmcli', 'd', 'wifi', 'connect', network, 'password', password
])
This way you also do not need to use extra quotes. 这样,您也不需要使用额外的引号。
Using shell=True
is advised against in the official documentation . 官方文档中建议不要使用shell=True
。
Just add "
to your variables, so shell wont treat backslash as newline escape. Something like 只需在变量中添加"
,这样shell就不会将反斜杠视为换行符。
'nmcli d wifi connect "{network}" password "{password}"'
In your example, you command equal to this: 在您的示例中,您命令等于:
nmcli d wifi connect abcnetwork password Pass|\
|ew2017;
If you copy-paste that into terminal - you will get exactly the same output as subprocess show ( except the python traceback ): 如果将其复制粘贴到终端中,则将获得与子进程show完全相同的输出(除了python traceback):
/bin/sh: 1: |ew2017: not found
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.