Farhanhasnat
Farhanhasnat

Reputation: 89

Python Subprocess Class

I am a learning Python and was trying the subprocess class from the tutorial. The tutorial uses MAC OS hence used ls -l . Since i am using Windows OS i used dir -d instead.

import subprocess subprocess.run(["dir", "-d"])

When ran the code in the terminal it prompts

 C:\Users\Farhan Hasant\Desktop\HelloWorld>dir -d
 Volume in drive C has no label.
 Volume Serial Number is 8296-8904
 Directory of C:\Users\Farhan Hasant\Desktop\HelloWorld
 File Not Found

Again, when i ran the code using code runner in VS code it shows

[Running] python -u "c:\Users\Farhan Hasant\Desktop\HelloWorld\app.py"
Traceback (most recent call last):
File "c:\Users\Farhan Hasant\Desktop\HelloWorld\app.py", line 3, in <module>
subprocess.run(["dir", "-d"])
File "C:\Users\Farhan Hasant\AppData\Local\Programs\Python\Python37\lib\subprocess.py", line 472, in run
with Popen(*popenargs, **kwargs) as process:
File "C:\Users\Farhan Hasant\AppData\Local\Programs\Python\Python37\lib\subprocess.py", line 775, in init
restore_signals, start_new_session)
File "C:\Users\Farhan Hasant\AppData\Local\Programs\Python\Python37\lib\subprocess.py", line 1178, in _execute_child
startupinfo)[![enter image description here][1]][1]
FileNotFoundError: [WinError 2] The system cannot find the file specified
[Done] exited with code=1 in 0.213 seconds

My files enter image description here

I am confused if I am doing it right. I would really appreciate your input on this. Thank you in advance.

Upvotes: 0

Views: 482

Answers (1)

yorodm
yorodm

Reputation: 4461

dir is not a real command in Windows, it's something builtin in the "shell" so you need to tell subprocess to launch a shell before attempting to run the command:

import subprocess
subprocess.run(["dir", "/d"],shell=True)

Also, follow @jasonharper comment about using / instead of - for most Windows native commands

Upvotes: 1

Related Questions