Os.system (<command>) execution via Python :: Constraints?

I am writing a python (version 2.7) script to automate the command set in this Getting Started example for INOTOOL .

Problem: When I run this whole script, I run into these errors repeatedly:

Current Directory is not empty  
No project is found in this directory  
No project is found in this directory  

      

But when I run the first script just before the marked line of code and manually type the next three lines, or when I run those last three lines (starting with the "ino init -t blink" line) after manually accessing the beep folder, I can successfully execute the same code.

Is there a limitation with os.system () that I'm running into?

My code:

import os,sys  
def upload()  
    os.system("cd /home/pi/Downloads")  
    os.system("mkdir beep")  
    os.system("cd beep") #will refer to this code junction in question description  
    os.system("ino init -t blink")  
    os.system("ino build")  
    os.system("ino upload")  
    sys.exit(0)

      

+3


source to share


2 answers


You can use the subprocess module and os.mkdir to create a directory, you can pass the current working directory cwd

to check_call

so you are actually running the command in the directory:

from subprocess import check_call
import os 
def upload(): 
    d = "/home/pi/Downloads/beep"
    os.mkdir(d)
    check_call(["ino", "init", "-t", "blink"],cwd=d)  
    check_call(["ino", "build"],cwd=d)  
    check_call(["ino", "upload"],cwd=d) 

      



Without a zero exit status will raise a CalledProcessError which you might want to catch, but once you know successfully, all commands returned a 0 exit status.

0


source


Yes, when the os.system()

commands are executed cd

it doesn't actually change the current directory for the context of the python process. From the documentation -

os.system (command)

Execute the command (line) in a subshell. This is implemented by calling the standard C () function system and has the same restrictions. Changes to sys.stdin etc. Not reflected in the environment of the executed command.

So, even though you change directory in the os.system () call, the next os.system call still occurs in the same directory. This can cause problems.



Try to use os.chdir()

to change directory instead of calls os.system()

.

subprocess

Better would be to use a module as @PadraicCunningham explains in his answer.

+1


source







All Articles