Rus Python script interactively

Marcus Wanner marcusw at cox.net
Sat Jul 18 19:04:07 CEST 2009


On 7/18/2009 12:32 PM, Gnarlodious wrote:
> In an interactive session (I am using iPython), what is the most
> elegant way to run a Python script from Terminal? Right now I am
> saying:
> 
> import subprocess
> subprocess.call("python /path/to/scriptname.py", shell=True)
> 
> But I am calling a shell process and I'd rather not. The script just
> runs, no inputs are needed. Is there a more Pythonesque method?
> 
> -- Gnarlie
> http://Gnarlodious.com/
You could put the code of the script in a main() function and have an if 
__name__ == '__main__': around the internal call. That way, it will 
still run the code if you run it normally, and you can also run it 
several times from the interactive session, ie:
file you want to run:
{{{
def somefunction():
	print 'hello world'

somefunction()
}}}
file after modifications:
{{{
def somefunction():
	print 'hello world'

def main():
	somefunction()

if __name__ == '__main__': #only true if the file is being run normally, 
not imported.
	main()
}}}
Both of those, if run normally, will print "hello world". If the first 
one is imported, it will run once and not me runnable in that session 
again. If the second one is imported, it will not do anything until you 
call the main() function, and then you can call it again as many times 
as you want:
{{{
 >>> import thefile
 >>> for i in range(5):
... 	thefile.main()
...
hello world
hello world
hello world
hello world
hello world
 >>> exit()
}}}
Hope this helps you!

Marcus



More information about the Python-list mailing list