Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to make my python function go to a specific folder path and run a command line

I am trying to automate my build process. typically what I do is I go to a certain folder where my make scripts are at, open a CMD, type a command which is something like this "Bootstrap_make.bat /fic = Foo"

Now I want to do this from inside my python code. simple question is How to do this, i.e. how to; using python code. go to a certain path > and open a CMD > and execute the command"

here is what I’ve tried

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

def myClick():
subprocess.run(["cd ..\Projects\ADAS\proj11\embedded_env\make_scripts" ])
subprocess.run(["bootstrap_make.bat","/fic= my_software_variant"])

However I git this error :

Traceback (most recent call last):
File "C:\Users\aelkhate\AppData\Local\Programs\Python\Python310\lib\tkinter_init_.py", line 1921, in call
return self.func(*args)
File "C:\E\ProductOne_Builder1.py", line 5, in myClick
subprocess.run(["cd ..\Projects\ADAS\proj11\embedded_env\make_scripts" ])
File "C:\Users\aelkhate\AppData\Local\Programs\Python\Python310\lib\subprocess.py", line 501, in run
with Popen(*popenargs, **kwargs) as process:
File "C:\Users\aelkhate\AppData\Local\Programs\Python\Python310\lib\subprocess.py", line 966, in init
self._execute_child(args, executable, preexec_fn, close_fds,
File "C:\Users\aelkhate\AppData\Local\Programs\Python\Python310\lib\subprocess.py", line 1435, in _execute_child
hp, ht, pid, tid = _winapi.CreateProcess(executable, args,
FileNotFoundError: [WinError 2] The system cannot find the file specified

>Solution :

You could use os.system().
https://docs.python.org/3/library/os.html

This code is assuming you are on Windows because you are running a .bat file and trying to open a CMD window.

import os

directory = './path/to/make/scripts'
buildCommand = './Bootstrap_make.bat /fic = Foo'

# if you don't want a new cmd window you could do something like:
os.system('cd {} && {}'.format(directory, buildCommand))

# if you want a new cmd window you could do something like:
os.system('cd {} && start "" "{}" '.format(directory, buildCommand))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading