From Python script how to run other Python script? - python

In my main Python script, I want to call another python script to run, as follows:
python2 ~/script_location/my_side_script.py \ --input-dir folder1/in_folder \ --output-dir folder1/out_folder/ \ --image-ext jpg \
From inside my Python script, how exactly can I do this?
I will be using both Windows and Ubuntu, but primarily the latter. Ideally would like to be able to do on both.

You could import the script in your main file.
Suppose you have two files: myscript.py and main.py
# myscript.py
print('this is my script!')
# main.py
print('this is my main file')
import myscript
print('end')
The output if you run main.py would be:
this is my main file
this is my script
end
EDIT: If you literally just want to call python2 my_side_script.py --options asdf, you could use the subprocess python module:
import subprocess
stdout = subprocess.check_output(['python2', 'my_side_script.py', '--options', 'asdf'])
print(stdout) # will print any output from your sidescript

Related

How to run python script from command line or from another script

I downloaded a script written in Python, called let's say 'myScript.py', but I don't know how to run it.
It has the following structure:
import numpy as np
import argparse
parser = argparse.ArgumentParser(description='manual to this script')
parser.add_argument('--file', type=str, default = None)
parser.add_argument('--timeCor', type=bool, default = False)
parser.add_argument('--iteration', type=str, default = 'Newton')
args = parser.parse_args()
def func1(file):
...
def func2(file):
...
def calculate(data, timeCor=False, iteration='Newton'):
...
if __name__ == "__main__":
print('\n--- Calculating ---\nN file:',args.file)
print('Time correction =',args.timeCor,
'\nIteration strategy =',args.iteration,'\n')
rawdata,data = func2(args.file)
pos = calculate(data,timeCor=args.timeCor,iteration=args.iteration)
for each in pos:
print('Pos:',format(np.uint8(each[0]),'2d'),each[1:-1])
np.savetxt('pos.csv',pos,delimiter=',')
print('--- Save file as "pos.csv" in the current directory ---')
How can I run it from command line? And from another script?
Thank you in advance!
If I understood your question correctly, you are asking about executing this python program from another python script. This can be done by making use of subprocess.
import subprocess
process = subprocess.run([“python3”, “path-to-myScript.py”, “command line arguments here”], capture_output=True)
output = process.stdout.decode() # stdout is bytes
print(output)
If you do not want to provide the command in a list, you can add shell=True as an argument to subprocess.run(), or you can use shlex.split().
If you are on windows, replace python3 with python.
However this solution is not very portable, and on a more general note, if you are not strictly needing to run the script, I would recommend you to import it and call its functions directly instead.
To run the python script from command line:
python myScript.py --arguments
And as #treuss has said, if you are on a Unix system (macOS or Linux) you can add a shebang to the top of the script, but I recommend to use the following instead:
#!/usr/bin/env python3
for portability sake, as the actual path of python3 may vary.
To run the edited program:
chmod +x myScript # to make file executable, and note that there is no longer a .py extension as it is not necessary
./myScript --arguments
Run it by executing:
python myScript.py
Alternatively, on systems which support it (UNIX-Like systems), you can add what's called a she-bang to the first line of the file:
#!/usr/bin/python
Note that /usr/bin/python should be the actual path where your python is located. After that, make the file executable:
chmod u+x myScript.py
and run it either from the current directory:
./myScript.py
or from a different directory with full or relative path:
/path/to/python/scripts/myScript.py

How to get PID of python process in windows

I want to run a python script from another python code in Windows. For this I am using "subprocess" module. Below are sample 2 python scripts.
app.py is as below,
#!/usr/bin/env python3
import subprocess
command = "python"
filename = "test.py"
args=[]
args.append(command)
args.append(filename)
output = subprocess.run(args)
and test.py is
import time
print("hello")
time.sleep(10)
When I run app.py, from subprocess test.py also runs. In ubuntu for both app.py and test.py separate PID s will be there.
But in Windows, I get PID of app.py but not of test.py.
I checked this command,
tasklist /v | FIND "test.py"
This gives empty result.
Can anybody help,
What should I do, so that I will get PID of test.py

How to run a python file while one python file is running

I have two files main.py& test.py
Suppose the main file main.py is running and after a point of time I want to run test.py
I cannot use:
import test or os.system("python test.py") because this run python file in same terminal but I want to run the test.py in other terminal
So I mean to say in one terminal main.py is running after a point a new terminal opens and run test.py
Any solutions?
Thanks :D
If I understand correctly you want to run a python script when some condition is fulfilled so I would recommend calling the "test.py" using a subprocess library (bear in mind there are other methods) like this:
import subprocess
if(your_condition):
subprocess.call(['python', 'test.py', testscript_arg1, testscript_val1,...])
as mentioned here: Using a Python subprocess call to invoke a Python script

How to send multiple commands to terminal(linux) from python?

I want to send commands to run a python script to the Linux terminal. I have a list of python files which I want to run and I want to run them one after the other as we read the list sequentially. Once the first file is finished, it should send the second one to run and so on.
You can run scripts sequentially using the following command:
python script1.py && python script2.py && python script3.py
&& runs the next script only if the previous has run successfully.
You can iterate through using the subprocess module:
import subprocess
script_list = ['script1.py', 'script2.py']
for script in script_list:
args = ['python', script]
p = subprocess.check_call(args)
You can use the check_call function of the subprocess module which is a blocking call. when you iterate through the list one will run after another.
import subprocess
files = ['script1.py', 'script2.py']
for _file in files:
call_output = subprocess.check_all(['python', _file])

run program in Python shell

I have a demo file: test.py.
In the Windows Console I can run the file with: C:\>test.py
How can I execute the file in the Python Shell instead?
Use execfile for Python 2:
>>> execfile('C:\\test.py')
Use exec for Python 3
>>> exec(open("C:\\test.py").read())
If you're wanting to run the script and end at a prompt (so you can inspect variables, etc), then use:
python -i test.py
That will run the script and then drop you into a Python interpreter.
It depends on what is in test.py. The following is an appropriate structure:
# suppose this is your 'test.py' file
def main():
"""This function runs the core of your program"""
print("running main")
if __name__ == "__main__":
# if you call this script from the command line (the shell) it will
# run the 'main' function
main()
If you keep this structure, you can run it like this in the command line (assume that $ is your command-line prompt):
$ python test.py
$ # it will print "running main"
If you want to run it from the Python shell, then you simply do the following:
>>> import test
>>> test.main() # this calls the main part of your program
There is no necessity to use the subprocess module if you are already using Python. Instead, try to structure your Python files in such a way that they can be run both from the command line and the Python interpreter.
For newer version of python:
exec(open(filename).read())
If you want to avoid writing all of this everytime, you can define a function :
def run(filename):
exec(open(filename).read())
and then call it
run('filename.py')
From the same folder, you can do:
import test

Categories