2

I'm sure this is something simple, but I'm trying several settings and I just can't seem to get this to work.

I have the following code:

import subprocess

p = subprocess.Popen('mkdir -p /backups/my_folder', stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True)

This is running in a flask application on nginx and python 3

When this executes I'm getting the following error:

/bin/sh: 1: mkdir: not found

I've tried with shell=False, I've tried with Popen(['mkdir', ...]), and I've tried subprocess.run like this question/answer

If I run with shell=False, I get the following error:

Error: [Errno 2] No such file or directory: 'mkdir -p /backups/my_folder': 'mkdir -p /backups/my_folder'

When I do /bin/mkdir, it works. But, there are other commands which call sub commands that fail (tar calling gz for instance)

What am I missing to get this to work?

Running:

Debian 9.8, Nginx 1.14.0, Python 3.6.8

EDIT

I need this to work for other commands as well. I know I can use os.makedirs, but I have several different commands I will be executing (rsync, ssh, tar, and more)

CodeLikeBeaker
  • 20,682
  • 14
  • 79
  • 108

3 Answers3

2

For these simple commands, try to use python instead of invoking the shell - it makes you more independent of the environment:

os.makedirs('/backups/my_folder', exist_ok=True)
nosklo
  • 217,122
  • 57
  • 293
  • 297
  • 1
    Thanks, I've updated my question to indicate that I need it on a general level. I have several commands I need to execute – CodeLikeBeaker Jun 14 '19 at 18:39
  • I still think going python is the solution @CodeLikeBeaker - you can open tar and gzip files directly from python too. `subprocess` module will try to find the programs in the `PATH` and if they are not there, there is nothing python can do – nosklo Jun 14 '19 at 18:39
1

I found the problem.

I realized that my /etc/systemd/system/site.service uWSGI settings had a hard coded path:

Environment = /usr/local/bin

Once, I changed this to include /bin, all my subprocess commands executed just fine.

CodeLikeBeaker
  • 20,682
  • 14
  • 79
  • 108
-1
import subprocess
p = subprocess.Popen('mkdir -p my_folder', stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True)
(result, error) = p.communicate()
print(result)

this is for only windows 10.

Jainil Patel
  • 1,284
  • 7
  • 16