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)
Related
I'll want to know how to call a function in vs code. I read the answer to similar questions, but they don't work:
def userInput(n):
return n*n
userInput(5)
And appends nothing
def Input(n):
return n*n
And in the terminal:
from file import *
from: can't read /var/mail/file
Can somebody help me?
You are doing everything correctly in the first picture. In order to call a function in python on vs code you first have to define the function, which you did by typing def userInput(n):. If you want to see the result of your function, you should not use return, you should use print instead. Return is a keyword- so when your computer reaches the return keyword it attempts to send that value from one point in your code to another. If you want to see the result of your code, typing print (n) would work better.
Your code should look like this:
def userInput(n):
print (n * n)
userInput(5)
The code would print the result 25
Your terminal is your general way to access your operating system, so you have to tell it that you want it to interpret your Python code first.
If you want to run the file you're typing in, you have to first know the location of that file. When you type ls in your terminal, does the name of your Python file show up? If not, hover over the tab in VSCode (it's close to the top of the editor) and see what path appears. Then in your terminal type cd (short for "change directory") and then the path that you saw, minus the <your filename here>.py bit. Type ls again, and you should see your Python file. Now you can type python <your filename here>.py to run it (provided you have Python installed).
You could also run the IDLE by just typing python in your terminal. This will allow you to write your code line-by-line and immediately evaluate it, but it's easier to write in VSCode and then run it with the method I described before.
I am revising a script that currently calls other scripts as subprocesses. Instead of doing that, I'm creating functions inside of the main script to perform the tasks previously performed by subprocesses.
One of the subprocesses required that variables be passed to it as you would from the command line.
Here is the code calling the subprocess:
subprocess.call("python cleaner.py < ./results/Temp.csv
>./results/result.csv", shell=True)
os.remove("./results/Temp.csv")
Here is what I'm trying to do:
def cleaner():
#working code that cleans certain characters out of selected
#.csv files.
function("./results/Temp.csv > ./results/result.csv", shell=True)
os.remove("./resluts/Temp.csv")
Ideally I'd like to use the existing code from the subprocess, but I'm open to changing it if that makes solving the problem easier. Here is that code:
from __future__ import print_function
from sys import stdin
print(next(stdin) , end='')
for line in stdin:
toks = [tok.replace("\'",""
).replace("text:u","").replace("number:", "") for tok in
line.split()]
print(' '.join(toks))
The script should clean the specified temp file, copy the cleaned version to a results file, then delete the temp file. Currently it works as a subprocess, but not when I try to run it as a function. I pass the variables incorrectly and it throws this error:
'TypeError: cleaner() takes no arguments (1 given)'
You need to define the arguments as part of the function.
def cleaner(argument1):
#working code that cleans certain characters out of selected
#.csv files.
Read more here.
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.
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?
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.