executing a python script from another python script

I have a script a.py :

#!/usr/bin/env python def foo(arg1, arg2): return int(arg1) + int(arg2) if __name__ == "__main__": import sys print foo(sys.argv[1], sys.argv[2])`

I now want to make a script that can run the first script and write the output of a.py to a file with some arguments as well. I want to make the automate_output(src,arglist) generate some kind of an output that I can write to the outfile :

import sys def automate_output(src, arglist): return "" def print_to_file (src, outfile, arglist): print "printing to file %s" %(outfile) out = open(outfile, 'w') s = open(src, 'r') for line in s: out.write(line) s.close() out.write(" \"\"\"\n Run time example: \n") out.write(automate(src, arglist)) out.write(" \"\"\"\n") out.close() try: src = sys.argv[1] outfile = sys.argv[2] arglist = sys.argv[3:] automate(src, arglist) print_to_file(src,outfile,arglist) except: print "error" #print "usage : python automate_runtime.py scriptname outfile args"

I have tried searching around, but so far I do not understand how to pass arguments by using os.system with arguments. I have also tried doing :

import a a.main()

There I get a NameError: name 'main' is not defined

Update : I researched some more and found subprocess and I'm quite close to cracking it now it seems. The following code does work, but I would like to pass args instead of manually passing '2' and '3' src = 'bar.py' args = ('2' , '3')
proc = subprocess.Popen(['python', src, '2' , '3'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) print proc.communicate()[0]

-------------Problems Reply------------

This is not a function, it's an if statement:

if __name__ == "__main__":

If you want a main function, define one:

import sys

def main():
print foo(sys.argv[1], sys.argv[2])`

Then just call it if you need to:

if __name__ == "__main__":

a.main() has nothing to do with if __name__=="__main__" block. The former calls a function named main() from a module, the latter executes its block if current module name is __main__ i.e., when a module is called as a script.

#!/usr/bin/env python
# a.py
def func():
print repr(__name__)

if __name__=="__main__":
print "as a script",

Compare a module executed as a script and a function called from the imported module:

$ python a.py
as a script '__main__'

$ python -c "import a; print 'via import',; a.func()"
via import 'a'

See section Modules in the Python tutorial.

To get output from the subprocess you could use subprocess.check_output() function:

import sys
from subprocess import check_output as qx

args = ['2', '3']
output = qx([sys.executable, 'bar.py'] + args)
print output

Category:python Views:0 Time:2011-10-14
Tags: python

Related post

  • Execute python script inside a python script 2010-08-05

    I have a scenario where i want to dynamically generate a python script - inside my main python script - store it as a string and then when need be, execute this dynamically generated script from my main script. Is this possible, if so how? thanks ---

  • Python: How can execute a jar file through a python script 2011-09-10

    I have been looking for an answer for how to execute a java jar file through python and after looking at Execute .jar from Python How can I get my python (version 2.5) script to run a jar file inside a folder instead of from command line? How to run

  • Execute /bin script from other python script 2011-11-11

    I have a script in my project's bin directory, and I want to execute it from a cron. Both scripts are written in python. Target file : App_directory/bin/script_name Want to execute script_name script with some parameters from App_directory/cron/scrip

  • Execute script from within python 2011-12-11

    I have a playgame.cmd file I would like to exceute from within my python code. It is a genetic algorithm that runs the game (input is individual), waits for the game to run with that individual, then parses data from the game log to output the fitnes

  • How do I use my standard python path when running python scripts from xcode macros 2008-12-13

    I'm trying to run Python scripts using Xcode's User Scripts menu. The issue I'm having is that my usual os.sys.path (taken from ~/.profile) does not seem to be imported when running scripts from XCode the way it is when running them at the Terminal (

  • Creating an interactive shell for .NET apps and embed scripting languages like python/iron python into it 2009-04-30

    I was learning python using the tutorial that comes with the standard python installation. One of the benefits that the author states about python is "maybe you’ve written a program that could use an extension language, and you don’t want to design a

  • Calling a non-returning python function from a python script 2009-06-30

    I want to call a wrapped C++ function from a python script which is not returning immediately (in detail: it is a function which starts a QApplication window and the last line in that function is QApplication->exec()). So after that function call

  • embedding short python scripts inside a bash script 2010-02-03

    I'd like to embed the text of short python scripts inside of a bash script, for use in say, my .bash_profile. What's the best way to go about doing such a thing? The solution I have so far is to call the python interpreter with the -c option, and tel

  • Python CGI Premature end of script error depending on script parameters 2010-04-19

    I have a python script which should parse a file and produce some output to disk, as well as returning a webpage linking to the outputted files. When run with a file posted from the HTML form I get no HTML output back, just a 500 error page and the e

  • how to run python script without typing 'python -' 2011-02-14

    I want to run a python script without explicitly having to call "python" every time in my shell. I've tried to add the shebang #!/path/to/python but this does not seem to work. Does anyone know a work around this? Many thanks. --------------Solutions

  • Embedding a Low Performance Scripting Language in Python 2011-02-24

    I have a web-application. As part of this, I need users of the app to be able to write (or copy and paste) very simple scripts to run against their data. The scripts really can be very simple, and performance is only the most minor issue. And example

  • How can i use nosetest to run an shell script or another python script 2011-04-17

    nose is a test runner which extends PyUnit. Is it possible to write e.g $ nosetests --with-shell myTest.py -myargs test If not, then is there a plugin, or do i need to develop it myself. Any suggestions ? --------------Solutions------------- Nose is

  • Run python script without the "python" keyword 2011-05-04

    How can I run a python script in Terminal on Mac without using the "python" keyword, without having to edit my existing python files? Right now I have to do this: python script.py What I like to do is this: script.py --------------Solutions----------

  • Invoking shell script from a python script using root privileges 2011-06-06

    I'm trying to invoke a shell script shell_script.sh from a python script (python_script.py) using the call command. The shell_script.sh invokes a executable that requires root access to execute. The python_script.py invokes shell_script.sh using subp

  • Calling a Python function from a shell script 2011-12-19

    I am trying to figure out how to call a Python function from a shell script. I have a Python file with multiple functions and I need to use the values returned by them in my shell script. Is there a way to do it. I am doing this in order to read a co

  • Python, communicating variables between a script and .exe 2011-12-26

    I have a python script: main.py, which executes a cx_frozen python script: test.exe I have created. main.py needs to send variables to test.exe. If the frozen script is able to send variables back that would be great too. I have, up to this point bee

  • How may one determine which version of Python is suitable for a script? 2013-04-01

    I want to determine which version of Python would be most appropriate for a Python script. Is there an automated way to do this? The specific problem I have in mind is to determine which version of Python to use with the script (called ea800_download

  • Python script embedded in shell script, does not exit and daemon solution does not fit the needs 2014-09-11

    This question extends/revives this one. The relevance to revive this topic is due to the failure in solving the same problem with the given answers. The bash script executes a python script embedded. Something like #!/bin/bash ./pyscript.py chmod +x

  • Return a list of imported Python modules used in a script? 2010-04-03

    I am writing a program that categorizes a list of Python files by which modules they import. As such I need to scan the collection of .py files ad return a list of which modules they import. As an example, if one of the files I import has the followi

Copyright (C) dskims.com, All Rights Reserved.

processed in 0.077 (s). 11 q(s)