Reputation: 86
I'm trying to run console command using python library subprocess. Here's what I get:
Python 3.8.3 (tags/v3.8.3:6f8c832, May 13 2020, 22:37:02) [MSC v.1924 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import subprocess
>>> import os
>>> os.system("echo Hello, World!")
Hello, World!
0
>>> subprocess.run(["echo", "Hello, World!"])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\trolo\AppData\Local\Programs\Python\Python38\lib\subprocess.py", line 489, in run
with Popen(*popenargs, **kwargs) as process:
File "C:\Users\trolo\AppData\Local\Programs\Python\Python38\lib\subprocess.py", line 854, in __init__
self._execute_child(args, executable, preexec_fn, close_fds,
File "C:\Users\trolo\AppData\Local\Programs\Python\Python38\lib\subprocess.py", line 1307, in _execute_child
hp, ht, pid, tid = _winapi.CreateProcess(executable, args,
FileNotFoundError: [WinError 2] The system cannot find the file specified
Upvotes: 0
Views: 4506
Reputation: 836
FileNotFoundError
indicates that the first argument in the subprocess.run list of arguments does not exist (in this case, 'echo' does not exist).
echo
is a shell command (not an executable) and according to the python documentation:
Unlike some other popen functions, this implementation will never implicitly call a system shell.
To address this, add the shell=True
argument:
subprocess.run(["echo", "Hello, World!"], shell=True)
EDIT: As noted in the comments, apparently non-Windows systems require all arguments to be a single string:
subprocess.run(["echo Hello, World!"], shell=True)
or
subprocess.run("echo Hello, World!", shell=True)
Upvotes: 1
Reputation: 189327
To run a shell command like echo
, you want shell=True
; and then the first argument should simply be a string, not a list of strings.
subprocess.run('echo "Hello world!"', shell=True)
Upvotes: 2