Python code runs interactively but not when run as script - python

I am new to python and have looked at similar questions but none seems to offer a solution to my simple case so I suspect I have made a basic error. I am using Python 2.7 on a Mac and on Ubuntu running on a Chromebook. When the project is complete I shall transfer it to a Raspberry Pi.
This snippet of code runs without a problem if I invoke the interpreter with the python call and type in the code.
switch = (int(time.strftime("%M"))%2
WhichOne = "Right","Left"
usbname = WhichOne[switch]
However, when I run the script containing this code fragment by typing ./project20160218.py or
python project20160218.py
I obtain
user#chrubuntu:~/Documents/Degree day project$ python project20160218.py
File "project20160218.py", line 23
WhichOne = "Right","Left"
^
SyntaxError: invalid syntax
I would be very grateful for some guidance here.
Thanks.

You're missing a closing parenthesis in the first line just before %2:
switch = (int(time.strftime("%M")))%2
WhichOne = "Right","Left"
usbname = WhichOne[switch]
If you close that it works. Also I assume you're importing time elsewhere, otherwise that would be undefined and also cause issues.

Related

I am new to python. I tried running a simple while loop but am receiving syntax error

I tried running the below code but VS Code is showing syntax error. I checked on internet and notes but found the loop is fine.
i = 1
while i <= 5:
print(i)
i = i + 1
While loop showing syntax error
I don't think there is anything wrong with your code but you should try to create a new folder preferably outside of Appdata. or One drive folder
There isn't anything wrong with your actual code. When I run it it executes as you would expect. I think the problem must be the way you are executing the program. I think you are attempting to run it in the python interpreter. Where it says "2:Python" you want it to be like "cmd" or "Code" or something and then you can just type in python loop.py maybe try clicking the plus next to it or select the first option in the dropdown.

Indentation error on Visual Studio Code on a Mac (again)

I am a newbie trying to use Python (2.17.15 via Anaconda) on Visual Stodio Code on my Mac. I have the following simple code:
def function(x):
y = x + 2
return y
This code is giving me the usual trouble, an indentation error:
return y
^
IndentationError: unexpected indent
>>> return y
File "<stdin>", line 1
return y
^
IndentationError: unexpected indent
>>>
Needless to say that Jupyter or Spyder have no problem with this. I checked that on VSC tab gives 4 spaces. All similar questions are related to this, but I cannot fix it.
Other, built in functions of Python work fine.
Please give me some help or tips since I do not know how to escape this.
UPDATE
Installing again Python3 this simple code DOES work on Sublime but still not on VS Code. I still get the same error in VS Code.
UPDATE2
So, another update. If I change from return to print and instead of shift-command debug and run the code then it works.
Any idea what is going on?
This looks like it's because you're running the code with Shift+ENTER.
VS Code has the following 2 bindings for Shift_ENTER:
I believe that you're seeing the 2nd of these, which says "Run Selection/Line in Python Terminal. I suspect you have the focus on the return y line, and so it's only running that single line of code.
If, instead of Shift+ENTER, you use the Run Code command in VS Code, you should see it work fine:
You might well think "OK...so if I select all of the code this will work, right?" and I agree...this feels like it should work. However, I see a similar issue. I'll see if I can work out why, but for the moment you can use the Run Code command in VS Code and that will do what you want. If you highlight the code you want to run, that will limit what gets executed.
Run Code can be executed with Ctrl+Alt+N
It looks like this issue (that selected code doesn't run correctly with Shift+ENTER) is a bug that's being tracked by here: https://github.com/Microsoft/vscode-python/issues/2837
And a work around (not ideal) is to add code before/after your function that is NOT indented, and then select and execute those lines too:
print("this...")
def function(x):
y = x + 2
return y
print("...now works if you select all these lines and Shift+ENTER!")
This is a bug from the python extension, which you need to run chunks of code in the interactive mode.
So in the example code below:
for lastRun in list(d_RunPanelsPresent.keys()):
# some indented commands
logFile = f"/nexusb/Novaseq/{lastRun}/logPPscript.txt"
if not os.path.isfile(logFile):
with open(logFile, 'w+') as f:
pass
else:
pass
If I highlight as follows (note where the cursor is):
I will get an error.
The solution is to highlight the code from the very left of the code editor, as shown below:
This works for me 100% of the time.
Forgetting a semicolon at the end of the function definition produces the same error.

Fatal Python error: Can't initialize threads for interpreter when calling python from c

I tried to call python code from c, the example runs ok for sample code on my environment(python3.6), but when I integrate it into my program, I got following error when I call Py_Initialize();:
...
sem_init: Success
Fatal Python error: Can't initialize threads for interpreter
Could you provide some clues to solve this problem?
It seems the error comes from here, but I am still not sure how to avoid this.
The failing code is
if (head_mutex == NULL)
Py_FatalError("Can't initialize threads for interpreter");
Searching the code back for head_mutex references finds
#define HEAD_INIT() (void)(head_mutex || (head_mutex = PyThread_allocate_lock()))
which is called right before the failing code.
So, the reason is that PyThread_allocate_lock returns NULL. There are a few different implementations for it in Python codebase depending on the OS and build flags, so you need to debug it or otherwise figure out which one is used in your case to track the error further to an OS call.
There is a function named sem_init in my program, which may conflict with the system library, the program runs ok after I modify the name of this function(but still not sure the reason).

second python execution fails

I'm having a problem embedding the python 3 engine for an app that need to run custom scripts in python. Since the scripts might be completely different, and sometimes user provided, I am trying to make each execution isolated and there is not need to preserve any data between execution of the different scripts.
So, my solution is to wrap each execution between Py_Initialize and Py_Finalize. It looks something like that:
void ExecuteScript(const char* script)
{
Py_Initialize();
PyRun_SimpleString( script );
Py_Finalize();
}
However, this fails for a particular python script the second time a script is executed with:
done!
Traceback (most recent call last):
File "<string>", line 8, in <module>
File "\Python33Test\Output\Debug\Python33\Lib\copy.py", line 89, in copy
rv = reductor(2)
TypeError: attribute of type 'NoneType' is not callable
The python script looks like this:
class Data:
value1 = 'hello'
value2 = 0
import copy
d = Data()
dd = copy.copy( d )
print ( 'done!' )
As you can see, the first time around the script was executed the 'done!' was printed out. But the second time it rises an exception inside the copy function.
It looks like the python engine was left in some weird state after the first initialize-finalize. Note, this is python 3.
Also, it is very interesting to note that Python 2.7 did not have this problem.
I guess there might be other examples that could reveal better what's going, but i haven't had the time to find yet.
Full sources of the test project can be found here:
https://docs.google.com/file/d/0B86-G0mwwxZvNGpoM1Jia3E2Wmc/edit?usp=sharing
Note, the file is 8MB because it includes the python distribution.
Any ideas of how to solve this are appreciated.
EDIT: I also put a copy of the project containing flag to switch between Python 3 and Python 2.7 (the file is 31 MB): https://docs.google.com/file/d/0B86-G0mwwxZvbWRldTd5b2NNMWM/edit?usp=sharing
EDIT: Well, I tested with Python3.2 and it worked fine. So it seems to be bug in Python3.3 only. Adding as an issue: http://bugs.python.org/issue17408#
Well, this was fast.
They actually found the issue being a problem in Python 3.3 code.
http://bugs.python.org/issue17408#

Python PyDev, Prevent carriage returns from input()

EDIT-4
I've gotten my sitecustomize.py to execute, but it tosses up an error. Here's the code for it.
The error is:
Error in sitecustomize; set PYTHONVERBOSE for traceback:
RuntimeError: maximum recursion depth exceeded while calling a Python object
I'm not terribly advanced with Python yet, so I figured I'd comment out only the lines I did not think Iwould need. No encoding issues are showing up, so I just commented out lines 23-104, but that didn't help either.
EDIT-3
I also happened to have 2.5.1 installed, so I compiled another script with that.
print 'This will test carriage returns on Windows with PyDev on Eclipse Helios'
print'Type something:',
test = raw_input()
print('You entered the following ascii values:')
for c in test:
print(str(ord(c)))
This ran fine, and resulted in
This will test carriage returns on Windows with PyDev on Eclipse Helios
Type something: g
You entered the following ascii values:
103
So this is possibly a Python3 thing only? I know it's not the interpreter, because I'm able to run it in command prompt just fine. What gives?
EDIT-2
Just tested with Helios, still having the same problem. Here's my test program:
print('This will test carriage returns on Windows with PyDev on Eclipse Helios.')
print('Type something:', end='')
test = input()
print('You entered the following ascii values:')
for c in test:
print(str(ord(c)))
And here's the output when I type 'g' and press Enter:
This will test carriage returns on Windows with PyDev on Eclipse Helios.
Type something:g
You entered the following ascii values:
103
13
In the grand scheme of things, it's a small issue. I could use input().rstrip() and it works. But the workaround shouldn't even be necessary. I'm typing twice as much as I should need to in a language that I'm using because it's concise and pretty.
EDIT-1
This is Eclipse 3.5. Unfortunately that's the latest version that's been approved for use at work. I'm going to try 3.6 at home to see if that's any different, but I wouldn't be able to use it anyway.
(original question)
I've been learning some basic Python, and decided to go with PyDev since it supported Python 3 as well as having all the nice code snippet and auto complete features.
However, I'm running into that darned carriage return issue on Windows.
My searches always lead me back to this mailing list:
http://www.mail-archive.com/python-list#python.org/msg269758.html
So I have grabbed the sitecustomize.py file, tried to include it in the Python path for my configured interpreter, as well as my project, but to no avail.
Has anybody else managed to work through this? Or maybe knows how to get the new sitecustomize.py to actually execute so it can override input() and raw_input()?
I know I could always make a short module with my own replacement input() function, but I'd really like to fix the problem at its root. Aptana acknowledges the issue ( http://pydev.org/faq.html#why_raw_input_input_does_not_work_correctly ) but offers no solution. Thanks in advance for your help.
Figured out a hack to make it work locally to my Python installation. In \Lib\site-packages\ make a script called "sitecustomize.py", and put this code in it:
original_input = builtins.input
def input(prompt=''):
return original_input(prompt).rstrip('\r')
input.__doc__ = original_input.__doc__
builtins.input = input
I don't know anything about the side effects of this, or what sort of error checking I should be doing, but it works if you're using PyDev on Windows to write scripts with Python3.
Found out some more things about sitecustomize.py and how it relates to site.py.
I don't know how to add my own sitecustomize.py to PYTHONPATH for execution only in a PyDev project, so I just stuck it in ${Python31dir}\Libs\site-packages. The module runs now, but generates errors.

Categories