After invoking Python from within Windows Powershell, I am unable to open files in the current working directory.
PS C:\python27> python
Python 2.7.9 (default, Dec 10 2014, 12:24:55) [MSC v.1500 32 bit (Intel
Type "help", "copyright", "credits" or "license" for more information.
After that, I type:
x = open(ex15_sample.txt)
With the idea of calling the open function on the filename parameter of the text file I would like to open in Python. The idea is that I can then run the following code in Windows Powershell and open that file in Python through Powershell:
print x.read()
However I can't get to this step, because after I typed
x = open(ex15_sample.txt)
Powershell outputs the following:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'ex15_sample' is not defined
In order to open the file "ex15_sample.txt" in Python via Powershell I also typed:
import ex15_sample.txt
After reading online that this can work, but Powershell outputted the following:
File "<stdin>", line 1, in <module>
ImportError: No module named ex15_sample.txt
How can I open the file "ex15_sample.txt" from within Python via the Powershell Command Line Interface?
You need to supply open() with a string.
"ex15_sample.txt" is a string literal, but ex15_sample.txt is the name of a variable you haven't defined yet.
So, you would need to type
open("ex15_sample.txt")
This is a pretty basic programming concept, and certainly not specific to Python. When you pass a value to a function like open, it can either be a variable containing a data, or a literal string. In this case, you want a string, and in most languages (including Python) strings must be surrounded by quotes:
x = open('ex15_sample.txt')
You've misunderstood what you've read about import: that's for loading other Python modules only.
Also note that none of this has anything to do with Powershell at all.
Think like this, when you run something, all the words in in it are commands (variables, functions, whatever), python will try to interpret all those things, when you try this:
open(ex15_sample.txt)
Python will effectively search for a command open (it will find, as it is a built-in function), and then it will search for another command ex15_sample that doesn't exist in python, so it will throw an error.
What you want to do is pass a text containing the name of the file to python, the way to do that is surrounding it with single or double quotes, either 'ex15_sample.txt' or "ex15_sample.txt", that way python interpret it as text instead of trying to understand it as a command, so
open('ex15_sample.txt')
is what you really want
Related
I've recently heard that you can change the prompt in python by changing variable sys.ps1. So I've decided to open IDLE, and write something like that:
>>> import sys
>>> sys.ps1 = ":::"
However, that created a new variable and nothing changed (prompt was still ">>>") - I rebooted IDLE and checked is this variable read by python... Nope:
>>> sys.ps1
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
sys.ps1
AttributeError: module 'sys' has no attribute 'ps1'
So, how do I change the prompt in python?
NOTE: The other functions/variables of sys module were read properly.
See issue #13657, "IDLE doesn't recognize resetting sys.ps1", on the Python bug tracker. It was opened in 2011 and is still unresolved (as of this writing). So it is not possible to change the prompt from within IDLE's Python shell simply because IDLE does not support that.
Update (less than 24 hours later): The issue is now closed. In the upcoming version of IDLE, to be released with Python 3.10, prompts will be displayed differently. See comment by IDLE developer Terry Jan Reedy above. A setting to change the prompt may be added in the future.
In the current and earlier Python/IDLE releases, the prompt can be customized before starting IDLE, but not while running it. You'd need a little start-up script that does this:
import sys
sys.ps1 = '::: '
import idlelib.idle
The reason you get that error message (module 'sys' has no attribute 'ps1') is because the Python shell that IDLE presents to you is not actually in "interactive" mode. And only then is sys.ps1 defined. You'd see the same error message if you tried to access sys.ps1 in any other Python program that is directly executed. In this case, that Python program is IDLE itself.
The prompt strings specifying the primary and secondary prompt (their initial values in this case are >>> and ... ) of the interpreter are only defined if the interpreter is in interactive mode and IDLE is more or less an integrated development environment for Python
Python interactive mode:
sys.ps1 doc
I use Python without a GUI/IDE by issuing Python from the Bash command line. I use it within a Cygwin environment, which behaves like a Linux system in many respects.
The file used for the history of commands issued at the Python command line is stored in ~/.python_history. I can easily scoot in and yank content for manipulation using vim's Buffer Explorer. It's also easy to yank manipulated content into the system clipboard for pasting at the Python command line. (For more tactical revisions of commands, on the other hand, I just use readline to vim previous commands and a single-line basis.)
I have found that ~/.python_history doesn't update after each command. I'm not sure how often it is updated, but it's clear that exiting Python causes it to update. Putting into the background with Ctrl+Z does not.
(Is there a quick and convenient way from the Python command line to force an update to ~/.python_history?
Since my original posting of this question, I've had occasion to figure out Linux (Ubuntu) as a VirtualBox virtual machine. However, it seems very excessive to fire up an entire guest operating system just to be able to access the command history as a palette as opposed to one line at a time using the Up-Arrow key (or equivalently, k if one's command line editor is set to Vim). I'd even be happy with a Python counterpart to Bash's "fix command" (fc) command, even though I would have to erase all the lines that I don't want to execute.
Various things tried
As per the responses, I tried importing readline.write_history_file, but it isn't recognized, even though readline itself is:
$python
Python 3.8.10 (default, May 20 2021, 11:41:59)
[GCC 10.2.0] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
# Show modules
>>> import sys
>>> modulenames = set(sys.modules) & set(globals())
>>> allmodules = [sys.modules[name] for name in modulenames]
>>> print(allmodules)
[<module 'sys' (built-in)>]
# Fail to import readline.write_history_file
>>> import readline.write_history_file as whf
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'readline.write_history_file'; 'readline' is not a package
# However, readline itself imports
>>> import readline
>>> readline.get_history_item(2)
'version'
readline does appear to be explicitly part of the Cygwin repository, so I didn't try pip install readline:
Search Cygwin packages for readline (followed by browser search for the string python)
The one result that appears to be most relevant shows dll,py, and pyc files with readline[s] in the file name, but I'm not sure what that says about the form taken by the readline module itself. I welcome clarifications/explanations about this.
In fact, I'm reluctant to try installing anything outside of the Cygwin package manager using pip for fear of creating inconsistencies.
Reading through this module, I found out readline.write_history_file(path) may be what you are searching for:
Save the history list to a readline history file, overwriting any existing file.
The default filename is ~/.history
First thing in the interactive interpreter, do
import readline.write_history_file as whf # write history file
Then you can do whf() or whf("path/to/.historyfile"), and your python history gets saved to disk immediately.
EDIT:
I'm not sure how often it is updated
It is only updated when you exit the interpreter. If you kill it, the history won't get saved, and Ctrl+Z just causes the interpreter to be suspended. If you then unsuspend it (by executing fg or bg, for example) and exit it normally, the history file will get written.
Python is very first programming language i'm learning , i'm following "python programming by John Zelle". The problem is that after creating module Chaos i'm not able to import this module, it shows error message that " Import error: No module name chaos.
I can see the confusion. I have actually read this book as well when I was learning. First be sure you launch python in the same directory as Chaos.py and be sure to use a capital C if that is how you named it.
To import it in the python interpreter you would not type import Chaos.py just import Chaos and then call the main function as follows:
import Chaos
Chaos.main()
If you wanted to run the script in python you can just type the following from a command line in the same directory as the .py file:
python chaos.py
(These directions assume Python 3 on Windows. If your system is different then please edit the question to tell your system and version.) First create a file named chaos.py on your desktop. In the file, paste the following:
# File: chaos.py
def main():
print("This program illustrates a chaotic function")
x = float(input("Enter a number between 0 and 1:"))
for i in range(10):
x = 3.9*x*(1-x)
print(x)
if __name__ == "__main__":
main()
Next, to make this as easy as possible, we will use a modified IDLE shortcut:
Copy your current IDLE shortcut and paste it to your desktop to create a new shortcut.
Right-click on the new shortcut and click Properties.
Change the Start In box to %USERPROFILE%\Desktop. Click OK.
Now open IDLE by clicking on the new shortcut. Then enter:
import chaos
chaos.main()
There's an easy solution, the way I got it to work was instead of making the module perform inside a IDLE environment, I opened up sublime text(a program similar to notepad++), and I essentially wrote the code inside of there and saved it as a python file called "Chaos.py" inside of the folder where IDLE runs, which is :
(C:\Users\ngltm\AppData\Local\Programs\Python\Python36-32\) )
, the name next after the "Users" will be different for you, but I saved it inside of the Python36-32 file and after saving it inside of sublime text, I opened up a IDLE program and wrote "import Chaos" and it worked! The problem was the text in the beginning of every IDLE file that starts off with :
"Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 16:07:46) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information."
Well, I hope this helped!
I am wondering, is there a way to change the name of a script so that it is not called "python.exe" in the tasklist. The reason I am asking is that I am trying to make a batch file that run's a python script. I want the batch file to check to see if the script is already running. if the script is already running then the batch file will do nothing. Thanks
Maybe you can try this : http://code.google.com/p/procname/
This library does not work on Windows, and shouldn't be used in production code. Manipulation the argv array is a rather dirty hack.
Generally I'd not try to identify processes by scanning the process table. This is not really reliable, as process names aren't guaranteed to be unique. Instead I'd spawn a simple server on localhost inside the python script. If started, the script can then try to connect to the server, and quit, if the server is already running. This approach can later on also be expanded to support any kind of IPC.
You could use py2exe to convert the Python script to a .exe file which means you could then give it any name you like.
Alternatively you could use Python itself (rather than a .bat file) using the approaches given at Reading Command Line Arguments of Another Process (Win32 C code) to determine the name of the scripts being run by the 'python.exe' processes.
I'd simply create a lockfile in the local filesystem and exit if this exists already.
Copy python.exe to a file name of your choice.
C:\Python26>copy python.exe my_proc.exe
1 file(s) copied.
C:\Python26>my_proc.exe
Python 2.6.5 (r265:79096, Mar 19 2010, 21:48:26) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
In the tasklist it is showing as my_proc.exe.
I've tried to make a symlink of python.exe (mklink in Windows 7). Unfortunately it is still showing as python.exe in the task list.
Python came pre-installed on my macbook and I have been slowly getting acquainted with the langauge. However, it seems that my configuration of the re library is incorrect, or I simply misunderstand something and things are amiss. Whenever I run a python script with "import re", I recieve the following error:
Traceback (most recent call last):
File "regex.py", line 2, in <module>
import re
File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/re.py", line 4, in <module>
# re-compatible interface for the sre matching engine
AttributeError: 'module' object has no attribute 'compile'
What gives!
Pretty mysterious problem, given that line 4 in that file (and many other lines around that line number) is a comment (indeed the error msg itself shows that comment line!-) so even with the worst misconfiguration I'd be hard put to reproduce the problem as given.
Let's try to simplify things and check how they may (or may not) break. Please open a Terminal, mkdir a new empty directory somewhere and cd into it (so we know there's no filename conflict wrt modules etc), at the bash prompt unset PYTHONPATH (so we know for sure that isn't interfering), unset PYTHONSTARTUP (ditto); then type the command:
$ python -c'import re; print re.__file__'
It should emit the line:
/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/re.pyc
does it? If so, then we can keep rooting around to understand what name clash (or whatever) caused your original problem. If the problem persists under such "clean" conditions then your system is jinxed and I would reinstal Mac OS X Leopard if I were in your shoes!