This question already has an answer here:
How to correctly pass subprocess arguments
(1 answer)
Closed 1 year ago.
I am trying to rename a drives volume label but i get an error if the label contains a space
import subprocess
subprocess.run(['label', 'L:test 1'])
Produces this Error:
Access Denied as you do not have sufficient privileges or
the disk may be locked by another process.
You have to invoke this utility running in elevated mode
and make sure the disk is unlocked.
The code works fine if I remove the space subprocess.run(['label', 'L:test1'])
How can I add spaces to my label?
try subprocess.run(['label', 'L:test', '1']).
It works via concatenation - silly, but true.
Related
This question already has answers here:
How should I write a Windows path in a Python string literal?
(5 answers)
Closed 2 years ago.
I have isolated a problematic part of my code and run it as 3 lines (see below), yet I still get this weird error where python tells me I used invalid argument, which looks different than the argument passed in. It apparently at random replaces one of my backslashes by double back slash (which shouldn't matter) and alters the name of the file i want opened.
Code:
fl = open("D:\test\sysi\temporary\fe_in.txt","rt")
flstr = fl.read()
ff = flstr.split("---")[1]
Error:
OSError: [Errno 22] Invalid argument: 'D:\test\\sysi\temporary\x0ce_in.txt'
Anybody has encountered this? Any ideas what could be causing this or what could I try? (I have already deleted and re-created the file in question thinking it could be corrupted, didn't change anything)
I tested it and I needed to use double slash "\\" to use this without your error:
fl = open("D:\\test\\sysi\\temporary\\fe_in.txt","rt")
flstr = fl.read()
ff = flstr.split("---")[1]
I believe it is because a single slash will be used as an escape character.
We do not know if your file is corrupted as you suspected in you question since the argument to "open" already was invalid. Your textfile was never opened before the error.
Now I only get, "[Errno 2] No such file or directory: 'D:\test\sysi\temporary\fe_in.txt'" because I did not place a file like yours in my file system, but if you have it the program should succeed.
try:
open(r"D:\test\sysi/temporary\fe_in.txt","r")
or
open(r"D:/test/sysi/temporary/fe_in.txt","r")
or
path = r"D:\test\sysi\temporary\fe_in.txt"
surely someone will work
This question already has an answer here:
Using subprocess.Popen (shell=True) with windows folders
(1 answer)
Closed 2 years ago.
The following code can open the test.txt file with notepad
subprocess.Popen(['start','test.txt'],shell=True)
But this won't open a file with a space in its name like 'the test.txt'.
I've tried using raw string(r'...'), double quote on cmd, '%20' to substitute the space, but none of that works.
Passing a list of arguments with shell=True happens to generally work on Windows, but is really never correct. Of course, start is a shell (cmd) command, so you need a shell here; but then, you also need to quote the string for the shell.
subproces.run('start "the test.txt"', shell=True)
Notice also that I switched to subprocess.run(); you generally want to avoid raw Popen whenever you can, as also suggested in the documentation.
It's much easier to rename the file with an underscore or dash etc.
I had a similar issue once with a client. I'm fairly certain we concluded by renaming by hand all of the necessary files to replace a space with an underscore.
Unless python have released a patch (or indeed, I was oblivious), I think it may be impossible.
Python reads a space and goes "okay, thats that command, what's next?" and then reads whatever follows the space, excluding certain things like string variables.
Take these lines
import os
os.system("start EXCEL.EXE my workbook.xlsb")
Python of course imports the os module here, then in line two it runs the os.system command with the parameters; start, EXCEL.EXE, my, workbook.xlsb
in fact it doesn't, once it reaches the filename "my" without an extension it quits and throws an error in the shell.
This question already has answers here:
How do I print colored text to the terminal?
(64 answers)
Closed 3 years ago.
How can I instruct python to generate an output file which keeps the color formatting specified in the main script?
I am working on the WRDS Cloud and I am using a shell file to execute a python script. The Cloud returns an output file which I can download and open like it is a txt file. However, this does not keep the color formatting that I specified in my original code.
I have tried to use different formatting packages in my python script but the result is always the same: the color is not displayed in the output file. I would really need to see the color because I use it to highlight some particular messages that represent warnings or errors. Therefore, I assume the only way around this is to instruct my python script to generate a different type of output, but I cannot figure out how.
my python script looks like this:
from colorama import *
init()
print(Fore.MAGENTA + 'Warning: The query failed' + Fore.RESET)
the output file looks like this (with no magenta color):
Warning: The query failed
The simple answer is that: "A simple text file cannot have different colors"
Colorama (and all the others terminal-color-suites) put "special characters" before the text that you want to color. Those caracters are "read" by the terminal that will output the correct character and the correct color (and also delete the special character so that the final user will never know that).
There is no way to color plain text because there is no one that "read" the special character and interpret them.
Also a protip for the future, dont import the whole library with a *, select the module you're going to use and import them explicitly like this:
from colorama import Fore
print(Fore.RED + 'some red text' + Fore.RESET)
This question already has answers here:
What is the python "with" statement designed for?
(11 answers)
Closed 4 years ago.
I've been reading the learn python3 the hard way book and in a exercise about python symbols he refers to a 'as' symbol and in the description it says "Part of the with-as statement" and the example format is "with X as Y: pass" but i couldn't find anything about such a thing online so I'm asking here.
Does anyone know anything about it?
and as a refrence it's exercise 37
The With x as y construct in python in called a context manager.
Context managers are used to properly manage resources. For example, if one is used to open a file, a context manager will ensure the file is closed.
with open('my_file.txt', 'r') as file:
for line in file:
print('{}'.format(line))
This is equivalent to:
file = open('my_file.txt') as file
for line in file:
print('{}.format(line))
file.close()
As you can see, the call to the close function is not necessary when you use a context manager.Its easy to forget to close the file, and this can lead to your system crashing if too many files are open. (There is a maximum number allowed by the operating system.)
See this link for more information and examples.
I have Python set up to create and open a txt file [see Open document with default application in Python ], which I then manually make some changes to and close. Immidiately after this is complete I want Python to open up next txt file. I currently have this set up so that python waits for a key command that I type after I have closed the file, and on that key, it opens the next one for me to edit.
Is there a way of getting Python to open the next document as soon as the prior one is closed (i.e to skip out having python wait for a key to be clicked). ... I will be repeating this task approximately 100,000 times, and thus every fraction of a second of clicking mounts up very quickly. I basically want to get rid of having to interface with python, and simply to have the next txt file automatically appear as soon as prior one is closed.
I couldn't work out how to do it, but was thinking along the lines of a wait until the prior file is closed (wasn't sure if there was a way for python to be able to tell if a file is open/closed).
For reference, I am using python2.7 and Windows.
Use the subprocess module's Popen Constructor to open the file. It will return an object with a wait() method which will block until the file is closed.
How about something like:
for fname in list_of_files:
with open(fname, mode) as f:
# do stuff
In case of interest, the following code using the modified time method worked:
os.startfile(text_file_name)
modified = time.ctime(os.path.getmtime(text_file_name))
created = time.ctime(os.path.getctime(text_file_name))
while modified == created:
sleep(0.5)
modified = time.ctime(os.path.getmtime(text_file_name))
print modified
print "moving on to next item"
sleep(0.5)
sys.stdout.flush()
Athough I think I will use the Popen constructor in the future since that seems a much more elegant way of doing (and also allows for situations where the file is closed without an edit been needed).