0

For some reason, I want to gather the help message of some commands. In order to do it, I use the subprocess module in Python3. My code works fine for linux commands but not when I use it on BASH commands. Typically I want it to work on the cd BASH command.

Here is the snippet of code I use for now:

import subprocess

instruction = ["cat", "--help"]
proc = subprocess.run(instruction, stdout=subprocess.PIPE,stderr=subprocess.PIPE, universal_newlines=True)
return proc.stdout

As said before, it works fine and it returns the help message of the command cat.

Here is what it returns when I try to adapt my code in order to handle BASH commands:

>>> import subprocess
>>> subprocess.run("cd --help", shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE).stdout
b''

My question is simple, is it possible to get BASH commands' help message using Python3. If so, how to do that ?

1 Answer 1

2

You can take a look at what subprocess.run returns:

>>> import subprocess
>>> result = subprocess.run("cd --help", shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
>>> result
CompletedProcess(args='cd --help', returncode=1, stdout=b'', stderr=b'/bin/sh: line 0: cd: --: invalid option\ncd: usage: cd [-L|-P] [dir]\n')

Turns out, cd --help is an error:

$ cd --help
-bash: cd: --: invalid option
cd: usage: cd [-L|-P] [dir]

So you should look for it in result.stderr.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.