Running a Python script from the Python Shell - python

I wrote a script and saved it as test.py (code shown below). And when I run it from the script (Run Module 5), I get the result in the Python Shell.
But I have tried multiple suggestions available online to have it run from the Python Shell instead to which I fail (one error pasted below).
How can I run a python script from the python shell?
The version of Python I am running is 3.7.3 and in Windows.
#!/usr/bin/python3
print(" Hello, world!")
exec(open(test.py).read())
Output:
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
exec(open(test.py).read())
NameError: name 'test' is not defined

You don't need the last line for it to run. All you need is:
!/usr/bin/python3
print(" Hello, world!")
If you want to run it from another file, don't use exec. Instead, import it.
import test

You need to pass the "test.py" as a string (use quotes).
test is not a known object.

Related

Applescript call python failed

I have developed an AppleScript which needs to call a python file. i.e autorun.py the Autorun.py start with
import msoffcrypto
import pathlib
import os
....
Both the AppleScript and the python file run fine. I even tried to call autorun.py in the terminal and that also runs with no problem. But when the Applescript tried to call the python file:
set myPythonScript to POSIX path of "/Users/zhouyu/Library/Application Scripts/com.apple.mail/autounlock.py"
set myVal to do shell script "python" & space & myPythonScript's quoted form
display dialog myVal
It failed at the first line in the python code when Applescript tried to call it.
error "Traceback (most recent call last):
File "/Users/zhouyu/Library/Application Scripts/com.apple.mail/autounlock.py", line 2, in
import msoffcrypto
ImportError: No module named msoffcrypto" number 1
Unlike Terminal.app, do shell script does not read your shell profile so make sure you give it the full path to your python interpreter, e.g.:
do shell script "/usr/local/bin/python3" & space & myPythonScript's quoted form

How to run a python program from python 3.8.0 IDLE shell

I want to launch the program Tip_and_Tax_Calculator.py from a folder named Python27 in a python 3.8.0 IDLE shell but I want to know which code will work. I have tried the exec function and execFile but they do not work, I don't know if I am using them in the wrong way too.
import Tip_and_Tax_Calculator
exec('C:\Python27\Tip_and_Tax_Calculator.py')
The error I get is:
Traceback (most recent call last): File "C:/Users/Jayan
Subramanian/AppData/Local/Programs/Python/Python38-32/Project
Launcher.py", line 1, in import Tip_and_Tax_Calculator
ModuleNotFoundError: No module named 'Tip_and_Tax_Calculator
you could use the exec function combined with open and read in the following way for python 3.x:
Notice I change from \ to /:
exec(open('C:/Python27/Tip_and_Tax_Calculator.py').read())
The method you tried and specified is relevant for python 2.x.
Another issue, you do not need to import the Tip_and_Tax_Calculator
EDIT
after the user added the error message the problem that the script didn't run is the fact the module Tip_and_Tax_Calculator is not in the current shell directory, so one need to specify its full/relative path

How to run a python script taking arguments with blender?

I have a script I want to run within blender to generate AO maps (script was given to me and the source guarantees it works).
I try to run the script as follows:
blender --background --python /opt/ff/product_builder/furniture_builder/generate_ao_maps.py --input_dir /tmp/test.obj --output_dir /tmp/test.png --mode ao
Which produces:
AL lib: (EE) UpdateDeviceParams: Failed to set 44100hz, got 48000hz instead
found bundled python: /usr/share/blender/2.79/python
Traceback (most recent call last):
File "/opt/ff/product_builder/furniture_builder/generate_ao_maps.py", line 195, in <module>
main()
File "/opt/ff/product_builder/furniture_builder/generate_ao_maps.py", line 178, in main
args = parse_args()
File "/opt/ff/product_builder/furniture_builder/generate_ao_maps.py", line 21, in parse_args
return parser.parse_args(os.getenv(BLENDER_ENV).split(' '))
AttributeError: 'NoneType' object has no attribute 'split'
Error: File format is not supported in file '/tmp/test.obj'
Blender quit
If I run this same script without blender (but with the argument) it tells me:
Traceback (most recent call last):
File "/opt/ff/product_builder/furniture_builder/generate_ao_maps.py", line 5, in <module>
import bpy
ImportError: No module named bpy
What do I need to do to pass the parameters to the script and get it working?
You are seeing that error because your script is looking for the environment variable BLENDER_ENV, which is not on your system. I don't recognize BLENDER_ENV as a standard Blender related environment variable so it's probable that your friend added BLENDER_ENV to his or her environment.
Firstly, blender processes its cli args in the order they are given, so your example will start in the background, run a script, then set the input_dir... This will most likely not have the result you are after.
The problem with your script failing is that the arg passed to os.getenv() needs to be a string that is the name of a shell environment variable, if you are using bash you need to export the variable to put it into the environment before you start blender.
export BLENDER_ARGS="arg1 arg2"
blender -b myfile.blend --python myscript.py
If you are using a csh then use setenv BLENDER_ARGS "arg1 arg2"
Then in your py script, you use os.getenv('BLENDER_ARGS').split(' ')
Note that each shell instance is a separate environment, you need to set the variables in the same instance that starts blender.
You may also be interested in passing cli arguments to the script as explained in response to this question.

Calling python script from a Bash script

I'm trying to call a python script from a bash script. I get import errors only if I try to run the .py from the bash script. If I run with python myscript.py everything is fine. This is my bash script:
while true; do
python script.py
echo "Restarting...";
sleep 3;
done
The error I get:
Traceback (most recent call last):
File "script.py", line 39, in <module>
from pokemongo_bot import logger
File "/Users/Paolo/Downloads/folder/t/__init__.py", line 4, in <module>
import googlemaps
ImportError: No module named googlemaps
There is more to this story that isn't in your question.
Your PYTHONPATH variable is getting confused somewhere along the way.
Insert a couple quick test lines:
in bash:
echo $PYTHONPATH
in your python:
import os
print os.environ["PYTHONPATH"]
At some point, the path to googlemaps got lost.
Your problem is in the script itself, your bash code is OK!. If you don't have problem running python scrip.py from bash directly, you should test if you use the same interpreter for both calls. You can check the shebang line in the python script, it is the first line in the file for example #!/usr/bin/env python or #!/usr/bin/python and compare it to the output of which python command if the output is different try to change or add the shebang line in to the file. If you call directly file in bash ./some_script.py bash reads the first line and if it is shebang line he wil execute the specific command for the file. My point is that if you use two diferent interpreters for calling file directly with python script.py and indirectly ./script.py one of them may not have the proper python modules.
Howto code:
$ which python
/usr/local/bin/python
So the second line is the path for your interpreter to build a shebang from it write in the first line of your script file this.
#!/usr/local/bin/python

Run Python File In Python Shell or Directly

I am just a beginner in Python. I created a file called as cc.py and saved in the following path :
C:/Python33/cc.py.
I am trying to run this file but nothing is happening.
In the python shell I am typing Python cc.py but I am getting the following error:
SyntaxError: invalid syntax
I tried an alternative :
>>> execfile('cc.py');
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
execfile('cc.py');
NameError: name 'execfile' is not defined
The file contains the following lines of code :
import urllib
htmlfile = urllib.urlopen("http://google.com")
htmltext = htmlfile.read()
print htmltext
How should I run this file? I am totally confused. Can someone help me out?
print htmltext should be print(htmltext). Also, execfile() was removed from Python 3. It seems you are using a Python 2 book but running Python 3. These different versions of Python are incompatible, stick to one. For choosing which version, see this question.
An implemention of execfile():
def execfile(filename, *args, **kwargs):
with open(filename) as fp:
exec(fp.read(), *args, **kwargs)
In python 3, execfile no longer exists. You can open it and execute it manually:
def xfile(afile, globalz=None, localz=None):
with open(afile, "r") as fh:
exec(fh.read(), globalz, localz)
And to execute:
>>> xfile(r'C:\path\to\file\script.py')
Credit to: What is an alternative to execfile in Python 3?
That's how you execute files from the interpreter.
Another way, you can execute it from the command prompt. Just open it and type:
$ cd filepath
$ python file.py
About the script you're running, there's also a confusion. Whatever example you are following, it's a Python 2 example, yet you are using Python 3. Change the request line to this:
htmlfile = urllib.request.urlopen("http://google.com")
Hope this helps!
You wrote:
In the python shell I am typing Python cc.py but I am getting the following error:
SyntaxError: invalid syntax
If you want to run the python script, don't do it from the python shell. The "python" (not "Python") command needs to be run from a command prompt (DOS shell, terminal window, etc).
From a command prompt you should issue the command:
$ python cc.py
For a more complete description of the problem and solution, see Executing Scripts in the windows section of the python user guide, and also How do I run a python program under windows in the frequently asked question section of the python users guide.
import urllib.request
with urllib.request.urlopen("http://www.yourwebsiteurl.com") as url:
htmltext = url.read()
print (htmltext)

Categories

Resources