I am trying to translate this from Bash to Python:
export file="${directory}/scrutation_$(date "+%Y%m%d_%H%M%S").log"
I know that export sets an environment variable, and that (date "+%Y%m%d_%H%M%S") is strftime("%d/%m/%Y, %H:%M:%S") in Python.
This is what I have tried:
import os
os.environ[file]= f"{directory}/scrutation[strftime("%d/%m/%Y, %H:%M:%S")].log"
Is this correct?
The name of the environment variable is a string, it needs to be quoted.
Double quotes aren't nested in f"", use single quotes for one of the pairs.
$(...) is the Command Substitution, i.e. you need to run the strftime, not include it in square brackets.
Also, you can use the same format string without changes, unless you really want to change the timestamp format.
os.environ['file'] = f'{directory}/scrutation_' \
f'{datetime.now().strftime("%Y%m%d_%H%M%S")}.log'
Related
I want to set a parameter for a python script by using the parameter field in PyCharm.
My config:
But the command in the Run console is:
python3 path_to_script.py '{app_id: picoballoon_network, dev_id: ferdinand_8c ... and so on
and not:
python3 path_to_script.py '{"app_id": "picoballoon_network", "dev_id": "ferdinand_8c" ... and so on
Basically, it deletes all " in the parameter.
Does anyone know how to turn this off?
My PyCharm version is:
PyCharm 2020.3.1 (Professional Edition)
Build #PY-203.6682.86, built on January 4, 2021
Runtime version: 11.0.9.1+11-b1145.37 amd64
VM: OpenJDK 64-Bit Server VM by JetBrains s.r.o.
Windows 10 10.0
To avoid the quotation marks being deleted notice the rules to writing parameters that contain quotation marks.
Run/Debug Configuration: Python
Configuration tab
When specifying the script parameters, follow these rules:
Use spaces to separate individual script parameters.
Script parameters containing spaces should be delimited with double quotes, for example, some" "param or "some param".
If script parameter includes double quotes, escape the double quotes with backslashes, for example:
-s"main.snap_source_dirs=[\"pcomponents/src/main/python\"]" -s"http.cc_port=8189"
-s"backdoor.port=9189"
-s"main.metadata={\"location\": \"B\", \"language\": \"python\", \"platform\": \"unix\"}"
The case in the question would be a single parameter, lets apply the rules to the example:
'{"app_id": "picoballoon_network", "dev_id": "ferdinand_8c"'
Because it's a single parameter containing spaces it has to be surounded by quotation marks.
Since the content of the parameter also contains quotation marks they must be escaped using a backslash \. So applying the parameter formatting rules gives:
"'{\"app_id\": \"picoballoon_network\", \"dev_id\": \"ferdinand_8c\"}'"
(Side note): In the example the parameter was surrounded by Apostrophes, this may be unnecessary and will probably have to be stripped later in your Python code (the below example uses the strip method).
You can test it with this simple script:
import sys
import ast
your_dictionary = ast.literal_eval(sys.argv[1].strip("'"))
(Side note): Your example parameter is a string containing a Python dictionary, there are several ways to convert it, in the example I included the highest voted answer from this question: "Convert a String representation of a Dictionary to a dictionary?"
A screenshot showing the parameter and test code in use:
I need to transform a string containing single and double quotes and newline characters for use in a system call. Consider the following input string:
"""one'two\nthree"four"""
This should be transformed to the following output string:
"$'one\'two\nthree\"four'"
So that it can be submitted as a message argument in a git commit command:
git commit --message=$'one\'two\nthree\"four'
The odd syntax with the leading $ and surrounding single quotes ' is a bash construct described in the bash manpage in the section on quoting (search for QUOTING). I have tried many python functions including str.replace, re.sub, json.dumps, repr, and str.encode('unicode-escape'). But none have yielded the required transformation. It seems that, in this case, python is too high-level for its own good. Suggestions on how to proceed will be very gratefully received.
The system call itself will be made using code like this (omitting the try block for clarity):
import subprocess
call = ["git", "commit", "--message", "'one\'two\nthree\"four'"]
cpi = subprocess.run(call)
I may also use a git library of some description, but I have not done my homework yet for that.
Note: the unnecessary $ character in the last item in the above call list has been removed.
Your wanted command is erroneous at the moment, it is not a valid Python string since a right " is missing, it should be:
"$'one\'two\nthree\"four'"
This is easily constructed by a simple .format call:
>>> "$'{}'".format("""one'two\nthree"four""") == "$'one\'two\nthree\"four'"
True
I am quite new to python and i struck an issue wherein, I am dynamically retrieving a string from a dictionary which looks like this
files="eputilities/epbalancing_alb/referenced assemblies/model/cv6_xmltypemodel_xp2.cs"
I am unable to to perform any actions on this particular file as it is reading the path as 2 different strings
eputilities/epbalancing_alb/referenced and assemblies/model/cv6_xmltypemodel_xp2.cs
as there is a space between referenced and assemblies.
I wanted to know how to convert this to raw_string (ignore the space, but still keep the space between the two and consider it as one string)
I'm not able to figure this out although several comments where there on the web.
Please do help.
Thanks
From the comments to the other answer, I understand that you want to execute some external tool and pass a parameter (a filename) to it. This parameter, however, has spaces in it.
I'd propose to approaches; definitely, I'd use subprocess, not os.system.
import subprocess
# Option 1
subprocess.call([path_to_executable, parameter])
# Option 2
subprocess.call("%s \"%s\"" % (path_to_executable, parameter), shell=True)
For me, both worked, please check if they work yor you as well.
Explanations:
Option 1 takes a list of strings, where the first string has to be the path to the executable and all others are interpreted as command line arguments. As subprocess.call knows about each of these entities, it properly calls the external so that it understand thatparameter` is to be interpreted as one string with spaces - and not as two or more parameters.
Option 2 is different. With the keyword-argument shell=True we tell subprocess.call to execute the call through a shell, i.e., the first positional argument is "interpreted as if it was typed like this in a shell". But now, we have to prepare this string accordingly. So what would you do if you had to type a filename with spaces as a parameter? You'd put it between double quotes. This is what I do here.
Standard string building in python works like this
'%s foo %s'%(str_val_1, str_val_2)
So if I'm understanding you right either have a list of two strings or two different string variables.
For the prior do this:
' '.join(list)
For the latter do this:
'%s %s'%(string_1, string_2)
I'm not quite sure when I need to put quotations around the filenames in Python.
For example, when I set
f = open(file)
I can run something like
len(f.read())
and it will run fine.
However, when I do it directly, it only works with
len(open("file").read())
Likewise, in terminal when running from Python I always have to use quotations.
What is the 'rule' when using quotations?
Thank you.
In python you can always use the name of a variable or function outside quotations, but the name of a file is usually not a variable.
If file is the name of a string variable you can always do open(file).read(), however if it is literally the filename you must always do open("file").read().
Quotations indicate a string literal constant. No quotations indicate that you're referencing a variable, which may itself be a string (in this case, populated with the path to a file).
I am trying to run a program from the command prompt in windows. I am having some issues. The code is below:
commandString = "'C:\Program Files\WebShot\webshotcmd.exe' //url '" + columns[3] + "' //out '"+columns[1]+"~"+columns[2]+".jpg'"
os.system(commandString)
time.sleep(10)
So with the single quotes I get "The filename, directory name, or volume label syntax is incorrect." If I replace the single quotes with \" then it says something to the effect of "'C:\Program' is not a valid executable."
I realize it is a syntax error, but I am not quite sure how to fix this....
column[3] contains a full url copy pasted from a web browser (so it should be url encoded). column[1] will only contain numbers and periods. column[2] contains some text, double quotes and colons are replaced. Mentioning just in case...
Thanks!
Windows requires double quotes in this situation, and you used single quotes.
Use the subprocess module rather than os.system, which is more robust and avoids calling the shell directly, making you not have to worry about confusing escaping issues.
Dont use + to put together long strings. Use string formatting (string %s" % (formatting,)), which is more readable, efficient, and idiomatic.
In this case, don't form a long string as a shell command anyhow, make a list and pass it to subprocess.call.
As best as I can tell you are escaping your forward slash but not your backslashes, which is backwards. A string literal with // has both slashes in the string it makes. In any event, rather than either you should use the os.path module which avoids any confusion from parsing escapes and often makes scripts more portable.
Use the subprocess module for calling system commands. Also ,try removing the single quotes and use double quotes.