import subprocess
import sys
def exec_cmd(cmd):
#Delete any spaces before or after the cmd string->Divide by space and make a list
cmd_split = cmd.strip().split()
#Get standard output with stdout settings
cp = subprocess.run(cmd_split, stdout=subprocess.PIPE)
# cp = subprocess.check_output(cmd_split)
if cp.returncode != 0:
print(f'{cmd_split[0]} faild.', file=sys.stderr)
sys.exit(1)
#Returns if there is standard output
if cp.stdout is not None:
return cp.stdout
Pass the command as it is as a string
cmd = 'touch file.py'
exec_cmd(cmd)
For lists, join () separated by spaces
files = ['file1.py', 'file2.py', 'file3.py', 'file4.py', 'file5.py']
files_sep_space = ' '.join(files)
cmd = f'touch {files_sep_space}'
exec_cmd(cmd)
Recommended Posts