Reputation: 327
My problem is that I want to execute a python file with an argument from inside another python file to get the returned values....
I don't know if I've explained it well...
example:
from the shell I execute this:
getCameras.py "path_to_the_scene"
and this return me a list of cameras....
so how can I call this script (including the argument) from another script ???
I've been trying to figure it out by myself by reading some other questions here , but I didn't get it well, should I use the execfile() function?? how exactly??
Thanks in advance for helping a newbie like me!!
Ok, after take a look at your answers, I have to edit my question to make it more concise and because I don't understand some answers(sorry, like I said I'm a newbie!!!):
I have two scripts, getMayaCameras.py
and doRender.py
, and one more, renderUI.py
, that implements the first two scripts in a GUI.
getMayaCameras.py
and doRender.py
are both scripts that you can execute directly from the system shell by adding an argument (or flags, in the doRender.py
case) and, if it is possible, I want to still having this possibility so I can choose between execute the UI or execute the script directly from the shell.
I've made already some modifications for them to work by importing them from renderUI.py
but now they don't work by themselves.
Is possible to have these scripts working by themselves and still having the possibility of calling them from another script? How exactly? This "separating the logic from the command line argument handling" that you told me before sounds good to me but I don't know how to implement it on my script (I tried but without success).
That's why I'm posting here the original code for you to see how I made it, feel free both to make critics and/or correct the code to explain me how I should make it for the script to work properly.
#!/usr/bin/env python
import re,sys
if len(sys.argv) != 2:
print 'usage : getMayaCameras.py <path_to_originFile> \nYou must specify the path to the origin file as the first arg'
sys.exit(1)
def getMayaCameras(filename = sys.argv[1]):
try:
openedFile = open(filename, 'r')
except Exception:
print "This file doesn't exist or can't be read from"
import sys
sys.exit(1)
cameras = []
for line in openedFile:
cameraPattern = re.compile("createNode camera")
cameraTest = cameraPattern.search(line)
if cameraTest:
cameraNamePattern = re.compile("-p[\s]+\"(.+)\"")
cameraNameTest = cameraNamePattern.search(line)
name = cameraNameTest.group(1)
cameras.append(name)
openedFile.close()
return cameras
getMayaCameras()
Upvotes: 24
Views: 97174
Reputation: 91
To answer your question (so how can I call this script (including the argument) from another script ???) simply:
You can run a script from another script together with its argument using the runfile() command as follow:
runfile("YourScript.py",args="Your_argument",wdir="Your working dir")
Upvotes: 0
Reputation: 52366
service1.py:
import test1
test1.some_func(1,2)
test1.py:
import sys
def some_func(arg1, arg2):
#all the code in def has to be indented, exit 0 if no error, exit code if error
# do something
print arg2
if __name__ == '__main__':
# test1.py executed as script
# do something
some_func(argv[1], argv[2])
Run:
python service1.py
python test1.py 3 4
Upvotes: -1
Reputation: 51
Another way that may be preferable to using os.system()
would be to use the subprocess
module which was invented to replace os.system()
along with a couple of other slightly older modules. With the following program being the one you want to call with some master program:
import argparse
# Initialize argument parse object
parser = argparse.ArgumentParser()
# This would be an argument you could pass in from command line
parser.add_argument('-o', action='store', dest='o', type=str, required=True,
default='hello world')
# Parse the arguments
inargs = parser.parse_args()
arg_str = inargs.o
# print the command line string you passed (default is "hello world")
print(arg_str)
Using the above program with subproccess from a master program would would look like this:
import subprocess
# run your program and collect the string output
cmd = "python your_program.py -o THIS STRING WILL PRINT"
out_str = subprocess.check_output(cmd, shell=True)
# See if it works.
print(out_str)
At the end of the day this will print "THIS STRING WILL PRINT"
, which is the one you passed into what I called the master program. subprocess
has lots of options but it is worth using because if you use it write your programs will be system independent. See the documentation for subprocess
, and argparse
.
Upvotes: 4
Reputation: 815
I suggest you reorganized your getCameras.py, wrap the get camera list code in a method called get_cameras(). Then you can call this method in other python scripts.
getCameras.py
def get_cameras():
bulabula...
if __name__ == '__main__':
return get_cameras()
How to use: other.py
import getCameras
camera_list = getCameras.get_cameras()
Upvotes: 0
Reputation: 71004
The best answer is don't. Write your getCameras.py as
import stuff1
import stuff2
import sys
def main(arg1, arg2):
# do whatever and return 0 for success and an
# integer x, 1 <= x <= 256 for failure
if __name__=='__main__':
sys.exit(main(sys.argv[1], sys.argv[2]))
From your other script, you can then do
import getCamera
getCamera.main(arg1, arg2)
or call any other functions in getCamera.py
Upvotes: 46
Reputation: 5957
First off, I agree with others that you should edit your code to separate the logic from the command line argument handling.
But in cases where you're using other libraries and don't want to mess around editing them, it's still useful to know how to do equivalent command line stuff from within Python.
The solution is os.system(command)
Atleast on Windows, it brings up a console and executes the command, just the same way as if you had entered it into the command prompt.
import os
os.system('getCameras.py "path_to_the_scene" ')
Upvotes: 10
Reputation: 798626
execfile()
runs one script within the other, which is not what you want. The subprocess
module can be used to run another instance of the Python interpreter, but what you should do is look at getCameras.py
and see if there's some function you can invoke after importing it.
Upvotes: 0