简体   繁体   中英

python - using backslash with subprocess.check_output

I am writing a script to connect to my wifi using Python in Ubuntu Operating System. 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. Instead, pass a list of arguments to 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 .

Just add " to your variables, so shell wont treat backslash as newline escape. Something like

'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 ):

/bin/sh: 1: |ew2017: not found

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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