Pass variable to python function from bash script - python

I am really struggling trying to figure out to pass variables from a bash script to a python function I have made. I have looked over numberous posts about the same issue and cant seem to understand what I am missing.
I have a python function script named fname_function.py:
from glob import glob
import os
import sys
first_arg=sys.argv[1]
second_arg=sys.argv[2]
third_arg=sys.argv[3]
def gFpath(reach,drive,date):
list1 = glob(os.path.normpath(os.path.join(drive, reach, date,'*')))
list2 =[]
for afolder in list1:
list2.append(glob(os.path.normpath(os.path.join(drive, reach, date, afolder, 'x_y_class?.asc'))))
return list2
if __name__=='__main__':
gFpath(first_arg,second_arg,third_arg)
And my bash script looks like:
reach="R4a"
drive= "D:\\"
dte="2015_04"
fnames=$(python fname_function.py "$reach" "$drive" "$dte")
for fname in $fnames; do echo "Script returned $fname"; done
The variables are being passed to the python script, but I cant seem to get list2 back to my shell script.
Thanks,
Dubbbdan

You can just run the Python file directly, like python fname_function.py "$reach" "$drive" "$dte"
However, sys.argv[0] will be fname_function.py in this case, so you'll want to set first_arg to sys.argv[1] and increment the other numbers as well.
Also, you don't output anything in your Python script. You should make the end of your script read:
if __name__=='__main__':
fnames = gFpath(first_arg,second_arg,third_arg)
for fname in fnames:
print(fname)
which will print out 1 result from gFpath on each line.

Related

The meaning of os.system in python

I am working to convert a code which is written in a code called " elegant" into another code.
I come by this lines, which i could not understand well, i am quit new to python
import os,sys
def computeOpticsD(quad_name, quad_id,k1):
ex = '/Users/ia/Products/elegant/darwin-x86/elegant'
args = ' compute_optics_d.ele -macro=lattice=fodo,quad_name='+quad_name+',quad_id='+str(quad_id)+',k1='+str(k1)
args += ',dir=data'
os.system(ex + args)
What dose it exactly do ?
os.system allow you to run OS commands as you would do for example in a script or in the terminal directly.
For example, if you run os.system("ls") it will return the list of files and directories in the location
In this case it seems your code fragment is trying to execute the following command in the OS:
/Users/ia/Products/elegant/darwin-x86/elegant compute_optics_d.ele -macro=lattice={fodo}, quad_name={quad_name}, quad_id={quad_id}, k1={k1}, dir=data
Where the elemnts in the key brakets come from your method parameters as defined in: def computeOpticsD(quad_name, quad_id,k1)

different result from F5 and F9 when running the os.path.realpath

I feel very confused about os.path.realpath(os.path.dirname(sys.argv[0]))
Here is my confusion:
(1) If I open my script in spyder (the first time) and run the selected lines below (F9):
import os
import sys
dir_path = os.path.realpath(os.path.dirname(sys.argv[0]))
It returns:
dir_path = C:\Python27\lib\site-packages\spyderlib\widgets\externalshell
which is not the result I want.
(2) However, if I run my whole script (F5), I can get what I expect (which is the current directory of my script):
dir_path = C:\Users\abc\Desktop\py
(3) Additionally if I:
Run the whole script,
%reset variables,
Run the same selected lines as before,
I can still get the current directory of my script, as long as I don't exit spyder:
dir_path = C:\Users\abc\Desktop\py
Gould anyone please explain something on this? It will be very appreciated. Thank you a lot!
To get your current complete pathname you can use
os.path.realpath(os.path.curdir)
As for the confusion, print the sys.argv to inspect it. Its content can hold different values, depending on how your script has been called. If I just enter into the python interpreter it holds a list with an empty string, but if I call python myscript.py, it will hold the script name followed by any arguments.

how to pass directory as arguments to python script using shell command?

I am trying to pass two directories to my python script which just prints out the directory. But somehow its not working. Below is the code
shellscript.sh:
set VAR1=$(pwd)
echo $VAR1
set VAR2=$(pwd)
echo VAR2
python.exe mypython_script.py "$VAR1" "$VAR2"
mypython_script.py:
import os
import sys
if __name__ = '__main__':
print(sys.argv[1])
print(sys.argv[2])
The echo is printing the path, but the terminal also does print the script call line. There its showing python.exe mypython_script.py '' '' and then print statements are printing empty string. Could anyone point out to me where the problem is? Thank you
Your problem is with
set VAR1=$(pwd)
You should use
VAR1=$(pwd)
instead.

Executing C++ code from python

I am a beginner to python, and I have no idea if this seems to be a doable thing.
I have a simple loop in python that gives me all the files in the current directory.
What I want to do is to execute a C++ code I wrote before on all those files in the directory from python
The proposed python loop should be something like this
import os
for filename in os.listdir(os.getcwd()):
print filename
(Execute the code.cpp on each file with each iteration)
Is there any chance to do this?
Fairly easy to execute an external program from Python - regardless of the language:
import os
import subprocess
for filename in os.listdir(os.getcwd()):
print filename
proc = subprocess.Popen(["./myprog", filename])
proc.wait()
The list used for arguments is platform specific, but it should work OK. You should alter "./myprog" to your own program (it doesn't have to be in the current directory, it will use the PATH environment variable to find it).

Running a script from another 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?

Categories