Running a script from another python - python

I just want to have some ideas to know how to do that...
I have a python script that parses log files, the log name I give it as an argument so that when i want to run the script it's like that.. ( python myscript.py LOGNAME )
what I'd like to do is to have two scripts one that contains the functions and another that has only the main function so i don't know how to be able to give the argument when i run it from the second script.
here's my second script's code:
import sys
import os
path = "/myscript.py"
sys.path.append(os.path.abspath(path))
import myscript
mainFunction()
the error i have is:
script, name = argv
valueError: need more than 1 value to unpack

Python (just as most languages) will share parameters across imports and includes.
Meaning that if you do:
python mysecondscript.py heeey that will flow down into myscript.py as well.
So, check your arguments that you pass.
Script one
myscript = __import__('myscript')
myscript.mainfunction()
script two
import sys
def mainfunction():
print sys.argv
And do:
python script_one.py parameter
You should get:
["script_one.py", "parameter"]

You have several ways of doing it.
>>> execfile('filename.py')
Check the following link:
How to execute a file within the python interpreter?

Related

How to run a .py file from a .py file in an entirely different project

For the life of me i can't figure this one out.
I have 2 applications build in python, so 2 projects in different folders, is there a command to say in the first application like run file2 from documents/project2/test2.py ?
i tried something like os.system('') and exec() but that only seems to work if its in the same folder. How can i give a command a path like documents/project2 and then for example:
exec(documents/project2 python test2.py) ?
short version:
Is there a command that runs python test2.py while that test2 is in a completely different file/project?
thnx for all feedback!
There's a number of approaches to take.
1 - Import the .py
If the path to the other Python script can be made relative to your project, you can simply import the .py. This will cause all the code at the 'root' level of the script to be executed and makes functions as well as type and variable definitions available to the script importing it.
Of course, this only works if you control how and where everything is installed. It's the most preferable solution, but only works in limited situations.
import ..other_package.myscript
2 - Evaluate the code
You can load the contents of the Python file like any other text file and execute the contents. This is considered more of a security risk, but given the interpreted nature of Python in normal use not that much worse than an import under normal circumstances.
Here's how:
with open('/path/to/myscript.py', 'r') as f:
exec(f.read())
Note that, if you need to pass values to code inside the script, or out of it, you probably want to use files in this case.
I'd consider this the least preferable solution, due to it being a bit inflexible and not very secure, but it's definitely very easy to set up.
3 - Call it like any other external program
From a Python script, you can call any other executable, that includes Python itself with another script.
Here's how:
from subprocess import run
run('python path/to/myscript.py')
This is generally the preferable way to go about it. You can use the command line to interface with the script, and capture the output.
You can also pipe in text with stdin= or capture the output from the script with stdout=, using subprocess.Popen directly.
For example, take this script, called quote.py
import sys
text = sys.stdin.read()
print(f'In the words of the poet:\n"{text}"')
This takes any text from standard in and prints them with some extra text, to standard out like any Python script. You could call it like this:
dir | python quote.py
To use it from another Python script:
from subprocess import Popen, PIPE
s_in = b'something to say\nright here\non three lines'
p = Popen(['python', 'quote.py'], stdin=PIPE, stdout=PIPE)
s_out, _ = p.communicate(s_in)
print('Here is what the script produced:\n\n', s_out.decode())
Try this:
exec(open("FilePath").read())
It should work if you got the file path correct.
Mac example:
exec(open("/Users/saudalfaris/Desktop/Test.py").read())
Windows example:
exec(open("C:\Projects\Python\Test.py").read())

How can i run a python 2.x function from a 3.x built with arguments? PSS/E

Hi I'm having a function that looks like it is only working in a 2.x (2.7) system. But the rest of my program is written in python 3.4
The file a.py (version 2.7) was a script i could run in 2.7 by calling the script as:
import psspy
openPath='busSystem.raw'
saveToPath='busSystem_out.raw'
#Open a case file
psspy.read(0,openPath)
do some calculation...
#Save to another case file
psspy.rawd_2(0,1,[1,1,1,0,0,0,0],0,saveToPath)
And then calling the following code from python 3.4 in b.py workes
import os
os.system('c:\python27\python a.py')
But then I wanted to change the script in a.py to be a function with kwargs such as:
def run(openPath='busSystem.raw',saveToPath='busSystem_out.raw')
#Open a case file
psspy.read(0,openPath)
do some calculation...
#Save to another case file
psspy.rawd_2(0,1,[1,1,1,0,0,0,0],0,saveToPath)
do something more...
So I want to do something like
import os
in = 'busSystem.raw'
out = 'busSystem_out.raw'
os.system('c:\python27\python a.py run(in, out)')
# Or
os.system('c:\python27\python a.py run(openPath=in,saveToPath=out)')
So the question is:
how can I send parameters to another script's function?
can I use both args and kwargs?
I know if I could have run the script with python 3.4 i could have just imported the function as
from a import run
run(in,out)
My solution for this would be to read the whole python script as a string, use str.replace('busSystem.raw',in) and str.replace(''busSystem_out.raw',out) and save it back as a a_new.py
and run it as mentioned before.
The script in a.py need to be in python version 2.7, because it is interacting with Siemens PSS/E 33, which only communicates through py2.7.
Function calls work only within a single process and, generally, only within a single language. So you have a script that can be run with no arguments. Now you want this script to process command line arguments. This has nothing, really, to do with function calls and keyword arguments.
You should read the Argparse Tutorial in the Python documentation. It introduces the concept of command line arguments, since you seem to be unfamiliar with it, and then shows some examples of using the built-in argparse module to do the hard parts of parsing the arguments.
Then you should read about the subprocess module. It will work better for you than os.system().
Alternatively, you could update the script so that works correctly in Python 3. This is what I would start with.
Here is some untested example code.
In your existing script a.py
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('openPath')
parser.add_argument('saveToPath')
args = parser.parse_args()
openPath=args.openPath
saveToPath=args.saveToPath
# ... the rest of the existing script
In your other program:
import subprocess
in_ = 'busSystem.raw'
out = 'busSystem_out.raw'
subprocess.call([r'c:\python27\python', in, out])

Python nosetests: how to access cmd line options? Namely `--failed`

Running: Windows 7, python 3.4 & 2.7
In one of my nosetests plugin, (one that post test data to a website), I need to ascertain if the test is being run with the --failed option or without. If --failed is enabled, that means this test failed the first time and is being run once more to see if that fail was a fluke. If this is a re-run of a failed test I need to direct my plugin to some different behavior vs. if the test is being run for the first time.
In other words, I want to ascertain inside the plugin if we are inside nosetests or nosetests --failed.
How can I access nosetest's command line options from inside a plug in? What variable are the options stored in?
My eventual code will look something like this:
if <--failed option was invoked with nosetests command>:
do something
else:
do something different
What's the correct code to replace what's inside <>?
I don't fully understand, but the command line arguments part is easy. Just use the following code:
from sys import argv as arguments
if "--failed" in arguments :
do_something()
else :
do_something_else()
When you import sys, you have access to the sys.argv
The simplest way to grab command line arguments is the system library
import sys
sys.argv #this is a list of args sys.argv[0] is the program itself
so it would be
if sys.argv[1] == '--failed':

Best way to call a python script from within a python script multiple times

I need to execute a python script from within another python-script multiple times with different arguments.
I know this sounds horrible but there are reasons for it.
Problem is however that the callee-script does not check if it is imported or executed (if __name__ == '__main__': ...).
I know I could use subprocess.popen("python.exe callee.py -arg") but that seems to be much slower then it should be, and I guess thats because Python.exe is beeing started and terminated multiple times.
I can't import the script as a module regularily because of its design as described in the beginning - upon import it will be executed without args because its missing a main() method.
I can't change the callee script either
As I understand it I can't use execfile() either because it doesnt take arguments
Found the solution for you. You can reload a module in python and you can patch the sys.argv.
Imagine echo.py is the callee script you want to call a multiple times :
#!/usr/bin/env python
# file: echo.py
import sys
print sys.argv
You can do as your caller script :
#!/usr/bin/env python
# file: test.py
import sys
sys.argv[1] = 'test1'
import echo
sys.argv[1] = 'test2'
reload(echo)
And call it for example with : python test.py place_holder
it will printout :
['test.py', 'test1']
['test.py', 'test2']

Running Python script from .BAT file, taking .BAT Filename as input

I got a Python script (test1.py) I need to run with a bat file (render.bat).
Question 1:
First, I had a definition in my test1.py and it always failed to run, nothing happened. Can someone kindly explain why?
import os
def test01 :
os.system('explorer')
and in the bat file:
python c:/test01.py
but as soon as I removed the def it worked. I just want to learn why this happened.
Question 2:
How can I take "render" string from render.bat as a string input for my python script so I can run something like :
import os
def test1(input) :
os.system("explorer " + input)
So the "input" is taken from the .BAT filename?
Functions don't actually do anything unless you call them. Try putting test01() at the end of the script.
%0 will give you the full name of the batch file called, including the .bat. Stripping it will probably be easier in Python than in the batch file.
Question1: Keyword def in python defines a function. However, to use a function you have to explicitly call it, i.e.
import os
def test01(): # do not forget ()
os.system('explorer')
test01() # call the function
1) You have to actually call the functions to achieve your task.
2) %0 refers to the running script. Therefor create a test.bat file like
# echo off
echo %0
Output = test.bat
You can strip the .bat extension from the output.

Categories