I'm trying to import a Python file containing a single function into my Julia notebook in VSCode.
The file is called helloPython.py and contains a single function called helloFromPython.
It contains the following code.
def helloFromPython():
print("Hello Julia, it's me Python!")
It is located in the same directory as my notebook file.
My first cell looks as follows.
import Pkg
Pkg.add("PyCall")
Pkg.build("PyCall")
using PyCall
Importing inbuilt Python functions works as expected, e.g.
math = pyimport("math")
math.sin(math.pi / 4)
Defining and calling Python code on the fly also works as expected, for example
begin
py"""
def f(x):
return x**3
"""
f = py"f"
end
f(2) # prints 8
However, importing my local Python file does not work. My cell looks as follows.
pushfirst!(PyVector(pyimport("sys")."path"), "")
x = pyimport("helloPython")
x.helloFromPython()
There is no error message. The cell executes successfully and that's it.
I've tried the same using the inbuild terminal in VSCode starting the Julia command prompt and it works as expected.
What am I doing wrong here?
Edit: #alex338207 had a good idea here, so I'm updating my question.
Writing to a file works. Here is a minimal working example. The file helloPython.py contains the following code.
def helloFromPython():
f = open("test.txt", "a")
f.write("Hello Julia!")
f.close()
Calling the above in VSCode as describe above, works as expected. A file is created with the provided content "Hello Julia!".
However, returning stuff doesn't work. Here is another example.
def helloFromPython():
return "Hello Julia!"
Calling the above yields to the output nothing.
I've updated my issue on Github.
Related
I am trying to use a Jupyter notebook that was written by somebody else around 8 years ago. And the contents are written in Python2 and not Python3 that I am using. I am new to it and I can't figure out the reason for the syntax error.
The following are the contents of the first cells that is giving a syntax error.
`# Always run this first
# NOTE: Do not define new basic variables in this notebook;
# define them in Variables_Q.ipynb. Use this notebook
# to define new expressions built from those variables.
from __future__ import division # This needs to be here, even though it's in Variables_Q.ipynb
import sys
import os
sys.path.append(os.path.join(os.path.dirname('/home/khushal/Desktop/Python/Git Repositories/PostNewtonian/PNTerms'
)) # Look for modules in directory above this one
exec(open('../Utilities/ExecNotebook.ipy').read(),{})
from ExecNotebook.ipy import execnotebook
try: execnotebook(VariablesNotebook)
except: execnotebook('Variables_Q.ipynb')`
The error is
File "/tmp/ipykernel_31372/53020713.py", line 11
exec(open('../Utilities/ExecNotebook.ipy').read(),{})
^
SyntaxError: invalid syntax
I tried to use a 2to3 jupter notebook converter but it didn't change the jupyter notebook at all and it is giving the same result.
How can I call a sconstruct script from R (e.g. in Rstudio)? I'd like to call SCons and, ideally, also read the output. So that I can get the print from e.g. scons --tree=all as a string.
If I run > system("scons")
I get: sh: scons: command not found
Setting the path Sys.setenv(PATH=paste(Sys.getenv("PATH"), "/path/to/my/sconstruct", sep=":")) doesn't help.
However, any other command works. E.g. if I have a Python script (in the same directory), I can call it as: > system('python test.py')
and get the expected: Hello Rld! back. >system('ls') lists the SConstruct, so I'm in the right work directory.
Calling from a Python script also works, eg: from subprocess import call call('scons') evokes the SConstruct as expected. However, calling that Python script from R -- doesn't work.
It appears as there is something in the R environment setting that I got wrong.
I'm on OS, but a portable solution would be fantastic!
You'll need to either be in the directory where the SConstruct is, specify it's file or use -C to change directory to it.
I don't know R or what the syntax is.
Sys.setenv(PATH=paste(Sys.getenv("PATH"), "/path/to/my/sconstruct", sep=":"))
Should likely be:
Sys.setenv(PATH=paste(Sys.getenv("PATH"), "/path/to/scons", sep=":"))
We're building an R codebase and are hoping to unittest any functions that we write. So far, we have found two testing libraries for R: RUnit and testthat.
After doing a bit of sandboxing, we have developed a solid method for testing code every time it runs. E.g.:
# sample.R
library(methods) #required for testthat
library(testthat)
print("Running fun()...")
fun <- function(num1, num2){
num3 = num1 + num2
return(num3)
}
expect_that(fun(1,2), equals(3))
Simple enough. However, we would also like the ability to test the function (with a unittest flag in a makefile for example) without running the script it is defined in. To do this we would write unittests in test.R
# test.R
source("sample.R")
expect_that(fun(2,3), equals(5))
and run it without running the rest of sample.R. But, when the code above is run, not only the functions but the rest of the code from sample.R will be run, in this example outputting "Running fun()...". Is there any way to source() only the user-defined functions from a file?
If not, would you recommend putting functions in a separate file (say, functions.R) which can be unittested by being sourced into test.R and run when sourced in sample.R? The drawback there, it would seem, is the boilerplate needed: a file for the process, a file for the functions, and a file to run the tests.
In each script, set a name variable that is defined only if it is not already defined. See exists(). I'm fond of __name__.
Create a main function in each script that only runs if the name is correct. This function contains everything you only want to run if this is the top level script.
This is similar to the python structure of
if __name__ == "__main__": main()
I didn't understand how to implement Will Beason's answer, but his mention of the pythonic way lead me to find this solution:
if (sys.nframe() == 0) {
# ... do main stuff
}
sys.nframe() is equal to 0 when run from the interactive terminal or using Rscript.exe, in which case the main code will run. Otherwise when the code is sourced, sys.nframe() is equal to 4 (in my case, not sure how it works exactly) which will prevent the main code from running.
source
I'm new to julia and just finished my first program. I wrote the code in julia-studio and have been testing it within that program. It gives me all of the correct output, but the shell separates the output as if it is two different executions.
I'm wondering if it's a problem with my compiler, so I thought I would try compiling it in the default julia shell found at julialang.org.
However, I cannot understand and/or figure out how to run it there. My current program reads input from another file in the same directory and outputs the results.
Can anyone explain how to run the program. This http://julia.readthedocs.org/en/latest/manual/getting-started/ isn't making sense to me.
Example output:
julia> program
#
#
#
#
julia>
#
#
#
#
#
The # represents integer numbers. Ideally the output should not be seperated by "julia>"
If you want to run the julia script from a command line then just do
/path/to/julia script-name.jl
In the shell of your choice.
If you want to run it from the julia repl then you want something like so:
julia> include("path/to/script-name.jl")
As to why your output is split like that I think we would need to see your code.
You can chmod your script and put the path to the julia binary at the to line.
Consider the following simple script hello.jl
#!/usr/bin/julia
println("Hello world")
change permission on the script using
chmod a+x hello.jl
Run the script using ./hello.jl
step 1: Open terminal
step 2: go to your Julia file location
step 3: execute the julia file
/path/to/folder script-julia.jl
Hit the up arrow, if it helps you. Thank you.
Look into using IJulia w/in Jupyter Notebook: https://github.com/JuliaLang/IJulia.jl
You're using the REPL. That works, but what I do is to go to command line and navigate to the folder like this (this is specifically for me, you will need to find the path directory to your file):
cd\users\yourname\desktop\code\julia
and to run the program:
julia filename.jl
its this simple (I guess)
You also can use IntelliJ IDEA with the plugin of Julia ... That's a surprise
if you want to import a Julia file to another Julia file, you should use the following command:
include("path-to-your-file.jl")
I am trying to recreate the demo examples on the IPython Notebook rmagic page. I am getting partial success with a specific error that comes up every time I try to use %Rpush or try to exchange data between R and numpy via the Rpush and Rpull mechanisms (which push/pull data between R and the Py namespaces )
%%R cell magic works reasonably well - I am able to define R vecs X and Y and do a print (lm(X~Y)) which successfully prints output in an IPython Notebook. This also works identically on the qtconsole, and the terminal.
Now if I do a plot(X,Y) inside the cell - I successfully get a plot.
If I start a new Notebook line and try plot(X,Y) I get the following error
[....]
TypeError: coercing to Unicode: need string or buffer, dict found
full stack trace at http://pastebin.com/Pb56Tmgc
a) Why is this successful inside a cell but not working in a line?
b) Any suggestions?
(Env: Python 2.7 (Anaconda 2.7.3 CE) R 2.15 rpy2 2.3 MacOSX 10.7.5 on a 2010 MBP 15"
http://www.soundfrost.org/ >youtube to mp3
This is a bug - the R magic was getting the local namespace as the argument where it was expecting the cell.
Digging into IPython.core.interactiveshell with git blame, it looks like it was fixed as part of pull request #2130 a few months ago.