0

I'm trying to execute a shell command using Python's subprocess. This is how I do it:

pelican = 'pelican content -s /home/pelican/publishconf.pyt -D --ignore-cache'
subprocess.call(pelican, shell=True)

But the response is command not found. It doesn't have a problem when I write in my command line.

My question is how can I execute a shell command using python that behaves just like I would type it in?

Badr Hari
  • 8,114
  • 18
  • 67
  • 100
  • 1
    try to `os.popen('your command')` – minji Sep 01 '17 at 00:18
  • 1
    Or try: `subprocess.call(pelican.split(" "), shell=True)` – Nir Alfasi Sep 01 '17 at 00:19
  • What does the split do in this case? With os.popen I get /bin/sh: 1: pelican: not found – Badr Hari Sep 01 '17 at 00:22
  • 2
    Sounds like there's a path issue, since the `pelican` command can't be found. Also, `.split()` causes a list to be returned with the parts of the command (`pelican.split(" ")` => `["pelican", "content", "-s", "/home/pelican/publishconf.pyt", "-D", "--ignore-cache"]`. It's generally a better approach since argument quoting can be done correctly (though I wouldn't necessarily use spilt to do this, try [shlex](https://docs.python.org/3/library/shlex.html))--as suggested in the [Frequently Used Arguments](https://docs.python.org/3/library/subprocess.html#frequently-used-arguments) docs. – John Szakmeister Sep 01 '17 at 00:32
  • Since the path appears to be a problem, it might be helpful to make sure that the path contains the pelican executable `subprocess.call("env", shell=True)`. – John Szakmeister Sep 01 '17 at 00:33
  • I did `which pelican` and got the abs path of pelican. Then the problem is all the imported modules give me errors, I wonder if its possible to just make it work like I would do it using the shell. – Badr Hari Sep 01 '17 at 00:47
  • 1
    `str.split` is not guaranteed to correctly parse a command line; consider `'pelican content -s "/home/pelican/my config.pyt" -D --ignore-cache'`. You should define a explicit *list* `["pelican", "content", "-s", "/home/pelican/my config.pyt", "-D", "--ignore-cache"]` and pass that as the first argument to `call` (with `shell=False`, the default, instead). – chepner Sep 01 '17 at 01:17
  • The issue is with your `PATH`, not with your code (though passing the command as a list with `shell=False` is [generally recommended](/questions/3172470/actual-meaning-of-shell-true-in-subprocess)) so you need to show us your `PATH`, the location of `pelican`, and the errors you get when you invoke it with the correct path (if it's a Python module, using `import pelican` would probably be a way better design). – tripleee Sep 01 '17 at 04:23
  • https://stackoverflow.com/q/5658622/1135424 – nbari Sep 04 '17 at 09:42

0 Answers0