简体   繁体   中英

AttributeError with python subprocess run

Python 3.7.1 64bit on Windows 7 64bit

test.py

import subprocess
subprocess.run(['ping localhost'], shell=True)

Output

C:\>python test.py
Traceback (most recent call last):
  File "test.py", line 2, in <module>
    subprocess.run(['ping localhost'], shell=True, check=True)
  File "C:\Program Files\Python37\lib\site-packages\run\__init__.py", line 145, in __new__
    process = cls.create_process(command, stdin, cwd=cwd, env=env, shell=shell)
  File "C:\Program Files\Python37\lib\site-packages\run\__init__.py", line 121, in create_process
    shlex.split(command),
  File "C:\Program Files\Python37\lib\shlex.py", line 305, in split
    return list(lex)
  File "C:\Program Files\Python37\lib\shlex.py", line 295, in __next__
    token = self.get_token()
  File "C:\Program Files\Python37\lib\shlex.py", line 105, in get_token
    raw = self.read_token()
  File "C:\Program Files\Python37\lib\shlex.py", line 136, in read_token
    nextchar = self.instream.read(1)
AttributeError: 'list' object has no attribute 'read'

Why am I getting this error and how do I fix this?

This is not specific to ping command but any trivial command for eg "dir"

After a lot of hit & trials and hair pulling, I got it working.

It should be instead

subprocess.run('ping localhost', shell=True) #Remove the square brackets

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