4

The subprocess.Popen() lets you pass the shell of your choice via the "executable" parameter.
I have chosen to pass "/bin/tcsh", and I do not want the tcsh to read my ~/.cshrc.
The tcsh manual says that I need to pass -f to /bin/tcsh to do that.

How do I ask Popen to execute /bin/tcsh with a -f option?

import subprocess

cmd = ["echo hi"]
print cmd

proc = subprocess.Popen(cmd, shell=False,  executable="/bin/tcsh", stderr=subprocess.PIPE, stdout=subprocess.PIPE)
return_code = proc.wait()

for line in proc.stdout:
    print("stdout: " + line.rstrip())

for line in proc.stderr:
    print("stderr: " + line.rstrip())

print return_code

2 Answers2

5

Make your life easier:

subprocess.Popen(['/bin/tcsh', '-f', '-c', 'echo hi'],
    shell=False, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
Michael Wild
  • 24,977
  • 3
  • 43
  • 43
0

I do not understand what the title of your question "Passing arguments to subprocess executable" has to do with the rest of it, especially "I want the tcsh to not to read my ~/.cshrc."

However - I do know that you are not using your Popen correctly.

Your cmd should either be a list or a string, not a list of 1 string.

So cmd = ["echo hi"] should be either cmd = "echo hi" or cmd = ["echo", "hi"]

Then, depending on if it is a string or list you need to set the shell value to True or False. True if it is a string, False if it is a list.


"passing" an argument is a term for functions, using Popen, or subprocess module is not the same as a function, though they are functions, you are actually running a command with them, not passing arguments to them in the traditional sense, so if you want to run a process with '-f' you simply add '-f' to the string or list that you want to run the command with.


To put the whole thing together, you should run something like:

proc = subprocess.Popen('/bin/tcsh -f -c "echo hi"', shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
Inbar Rose
  • 41,843
  • 24
  • 85
  • 131
  • _Then, depending on if it is a string or list you need to set the shell value to True or False_ - I think you got it backwards. First, you need to decide whether you need to run your command(s) through a shell or not (typically, you don't). This then determines how you should pass in your commands. – Brecht Machiels May 30 '23 at 13:32