AB567
AB567

Reputation: 141

how to run both a .py and a .exe file from the same python script

I am wondering how to run both a .py and a .exe file from the same python script.

I have a script that works for running the .py and a script that works for running the .exe.

My problem is that I don't know how to run them from the same script! I would like the exe file to occur between the two .py files.

.py script

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from __future__ import division  # so that 1/3=0.333 instead of 1/3=0
from psychopy import visual, core, data, event, logging, sound, gui
from psychopy.constants import *  # things like STARTED, FINISHED
import numpy as np  # whole numpy lib is available, prepend 'np.'
from numpy import sin, cos, tan, log, log10, pi, average, sqrt, std, deg2rad, rad2deg, linspace, asarray
from numpy.random import random, randint, normal, shuffle
import os  # handy system and path functions

"""find and execute all .py files in the current directory"""

import glob, sys
import subprocess
import random


def launch(exp):
    """launch a compiled PsychoPy experiment (.py) via subprocess"""
    command = [sys.executable, '-u', exp] # spaces in file names are ok
    proc = subprocess.Popen(command)
    proc.communicate()
    del proc


expts = ['myPythonFile1.py', 'myPythonFile2.py']
for exp in expts:
    launch(exp)

.exe script

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from __future__ import division  # so that 1/3=0.333 instead of 1/3=0
from psychopy import visual, core, data, event, logging, sound, gui
from psychopy.constants import *  # things like STARTED, FINISHED
import numpy as np  # whole numpy lib is available, prepend 'np.'
from numpy import sin, cos, tan, log, log10, pi, average, sqrt, std, deg2rad, rad2deg, linspace, asarray
from numpy.random import random, randint, normal, shuffle
import os  # handy system and path functions

import subprocess

a=subprocess.Popen(r"myEXEfile.exe")
a1=os.system(r"myEXEfile.exe")

Upvotes: 0

Views: 212

Answers (1)

Raydel Miranda
Raydel Miranda

Reputation: 14360

Just check for each type.

def launch(exp):
    # check if exe or py
    if (exp.endswith(".exe")):                  # So it's an exe.
        a=subprocess.Popen(exp)
        a1=os.system(exp)
    else:                                       # Otherwise is a .py        
       # Launch a compiled PsychoPy experiment (.py) via subprocess.
        command = [sys.executable, '-u', exp] # spaces in file names are ok
        proc = subprocess.Popen(command)
        proc.communicate()
        del proc 

# And just put your exe filename between the two py files. 
expts = ['myPythonFile1.py', r'myEXEfile.exe', 'myPythonFile2.py']
for exp in expts:
    launch(exp)

Besides, if you aren't using process output I recommend you use proc.wait() instead proc.communicate

Upvotes: 1

Related Questions