How to execute Python file - python

I am learning Python and DJango and I am relatively nub with Linux. When I create DJango project I have manage.py file which I can execute like ./manage.py runserver. However when I create some Python program by hand it looks like that my Linux trying to execute it using Bash, not Python. So i need to write python foo.py instead ./foo.py. Attributes of both files manage.py and foo.py are the same (-rwx--x---). So my Q is: where is difference and how I can execute python program without specifying python? Links to any documentations are very appreciate. Thanks.

You missed one step, after give the corrects permissions to the file, open your foo.py then put this on the first line
#!/usr/bin/env python
Then you can use ./foo.py

I am just gonna add this for more clarity and to anyone coming across this post who might need an explanation.
Why do people write #!/usr/bin/env python on the first line of a Python script?
explains why you should it is used.

Save your python code file somewhere, using "Save" or "Save as" in your editor. Lets call it 'first.py' in some folder, like "pyscripts" that you make on your Desktop. Open a prompt (a Windows 'cmd' shell that is a text interface into the computer): start > run > "cmd".

Related

How do force or change my terminal to run python executable file in python 3 just by opening the file?

My terminal is running python 2 so when I run my python file the program fails.
So basically I am new to programming and trying to create a small python script to help me auto create folders. I also want to give the script to colleges so that they can use it on their systems too.
I know that I can run my file in terminal by using "python3 myfile.py" and it will work, but that's too much off a mission to do for my colleges and as my colleges are not familiar with code or terminal for that matter, I wanted to create an executable file so that they just click to open type a few answers to the promoted question and boom folders created.
This is where I run into a problem, I have "#!/usr/bin/env python3" at the top of my file but when I run the script IDLE opens up and it just shows the code I have written but doesn't seem to run the actual script I wrote. Am I doing something wrong?
I also then though perhaps I could just use the terminal to run the file as it is now executable, so I go into terminal and enter "myfile.py" and the program runs but in python 2 so my script fails as it is in python3. So another question would be is there a way to code into my python file, when running this file make sure you use python3? as I would want this to work on all colleges system without them having to write out anything in terminal?
Sorry for the long explanation but any advice would be greatly appreciated.
Thank you in advance
When you are on windows you can just create a .bat file where you write: python3 myfile.py in it.
Both files have to be in the same directory.
If you want to have a .exe you can also use py2exe.
You could also try just #!/usr/bin/python3 without env.
More here.

Python: Is there any way I can take a script and import it's contents to idle in order to edit them there?

I have a little a script containing some "dictionaries".
"Is there any way I can take this script and import it's contents to idle?"* using a command like import.
What want to do then is to edit (or view) these dictionaries "live" in idle.....
Copy paste the script into the shell. Make sure there are no blank lines inside indented blocks or you'll get a SyntaxError.
Yes, import command should work: Just put "import myScript". You can add a path to your script with a line like sys.path.append(r"D:\myPath") before that statement
If you are on Windows right click on the script > Open with > Choose your Idle if it's there if not click on more(not sure what it's named it's the last option) then there should be some more options to open the file if your idle is still not there you can browse your files and go to the folder where your idle is saved and choose the exe to open the script in the Idle
Well I have to confess that I use linux mint, so there's no such thing as idle and that is why I use the terminal (where I type python3) to code instead! To make it clear, what I wanted to do is to take a script which contains a dictionary and some functions and then run it in terminal in order to use those functions there. The import command has nothing to do here!!!The answer is to use the exec commmand!!! Here is a picture:1. My question was not clear......
P.S Mushroommaula answered the question.

Rundeck :: Execute a python script

I am new to Rundeck, so I apologize if I ask a question that probably has an obvious answer I'm overlooking.
I've installed Rundeck on my Windows PC. I've got a couple of Python scripts that I want to execute via Rundeck.
The scripts run fine when I execute them manually.
I created a job in Rundeck, created a single step (script file option) to test the python script.
The job failed after six seconds. When I checked the log, it was because it was executing it line by line rather than letting python run it as an entire script.
How do I fix this?
You had to put:
#!/usr/bin/python
or similar, with location to your python binary, as 1st line. To indicate which interpreter to use for whole file.
okay, so I changed the step type to a command rather than script file and it worked.
I guess my understanding of what a script file is was off.

Unable to run .py file from putty, Syntax error: word unexpected (expecting ")")

I am new to both Python and Linux and as such request simple explanations with minimal assumed knowledge where possible please, however I am more than willing to invest time and effort to learn.
I have a Raspberry Pi 2 (Model B V1.1) that is running Linux. I interact with this pi via putty.
I am trying to create a simple competitive reflex game, consisting of 2 buttons and a single LED. My goal is to have the LED light up after a short interval, and the first player to press their button wins.
I am writing the script for this with python (specifically 2.7.3)
My issue is that i am unable to run ANY .py file from within putty, i always receive the same error:
Syntax error: word unexpected (expecting ")")
To determine if the issue was an error in my code, i created a very very simple .py file, to check if the same error occurs, and it did. So i currently believe even if my code was functional, something is stopping me from running ANY .py file.
The process I am using is as follows:
First I create a new python file from within putty:
sudo nano test.py
Next I enter my python code (very simple for now, as i cannot get ANY .py file to run)
for each in range(5):
print 'hello'
I then press CTRL + O to write the file, hit enter, then CTRL + X to exit
Finally, I make the file executable using
sudo chmod u+x test.py
and try to run it
sudo ./test.py
again, a similar error occurs
Syntax error: "(" unexpected
I then decided to enter the code directly into the python shell, using
sudo python
>>>for each in range(5):
... print 'hello'
This time the output is the desired outcome:
hello
hello
hello
hello
hello
So there is no problem in executing python code directly from the shell, I am just unable to execute any previously saved .py file
Any insight into what could be causing this is much appreciated, and I apologise if I have not provided enough information to be useful for you.
Thanks in advance!
Short answer: Either run these as python filename.py, or else add the line #!/usr/bin/python to the top of your Python scripts.
Long answer: When you run a file from the command line in Linux (which is what the Raspberry Pi is running), by default it assumes that the file is a shell script file (usually Bash script). So it uses the Bash shell (or some other shell, but it's usually Bash) to interpret the file, and Bash doesn't know Python syntax. If you want to run your file using a different interpreter (Python, in this case), you have to add a "magic line" at the top of the file starting with #! (usually pronounced "hash-bang", and sometimes pronounced "shebang" for short). Following the #! characters is the full path of the interpreter to use, e.g. /usr/bin/python for Python scripts. (You can also use /usr/bin/env python as another answer suggested; I prefer /usr/bin/python because it's impossible to get the wrong Python interpreter that way. But that's getting into advanced topics that may be more than you need right now.)
So when you put the line #!/usr/bin/python at the top of your Python scripts, you're telling the Linux system which interpreter to run the program with, and then it should All Just Work™.
Also, STOP using sudo to edit and run these! That's just asking for trouble.
If you wish to execute like this you need the following line as the first line
#!/usr/bin/env python
This will tell bash (or equivalent) to execute the file with the Python interpreter.
If you don't want to do that then you can execute the script like this:
$ python test.py
If you go this route then you don't need to grant execute permissions on the script itself.
Also, scripts shouldn't be executed with sudo unless absolutely necessary.

How to get out of interactive mode in Python

This obviously an extremely novice question, but I've installed Python 2.7 and started reading the manual. However I looked and looked, and couldn't understand how to start programming a file rather than writing in interactive mode. One book that was online suggested quit(), which surprise -- quit the program.
Should coding be done in a different program? I'm using IDLE (Python GUI). Can coding not be done within that program?
Yes, coding should be done in a different program. The interactive shell is very useful but it's not an editor.
You write Python code line by line (as you would on Python interactive mode) in a text editor such as vim, emacs etc...
Then you run these line by line code using the Python interpreter by giving it the name of your script.
$ python myscript.py
I like to use a different directory for each project. Suppose I decide to use W:/mytest as my directory. First I create the directory.
Then I start Idle. I type the following:
import os
os.chdir("W:/mytest")
This makes W:/mytest the current directory for Idle.
import sys
sys.path.append(".")
This changes the path so that when I "import", it will look in the current directory.
Next I do File / New Window to open an editor window, and in that new window I select File / Save As. It starts in the Python home directory so I have to navigate to W:/mytest. I save this (empty) file as "test1.py".
I type this into my test1.py file and save it again:
""" test1.py is my test
"""
print ("This is test1.")
class Test1:
def __init__(self):
print ("Constructed")
This is a contrived example that can be run as a script or imported as a module.
So I have two windows now; an editor window and the Idle "Python Shell". I can do this in the Python Shell:
>>> execfile("test1.py")
This is test1.
>>> import test1
This is test1
>>> tt = test1.Test1()
Constructed
Push new to start making your own script file. Then when you are ready to test click run and then you can watch the results in the interactive mode, and even try new things as if you were adding code to the end of your script file, its a very useful app for debugging, testing and trying new things.
Also in the options you can change the way python opens your scripts when you click edit from windows, you can set it so that it opens the interactive shell or just the editor.
use new window tool in the file icon,in the python idle itself to write a program
To start coding in a file, just open a new file and start typing.

Categories

Resources