Is using Python f-strings effective for generating Python code?Calling an external command in PythonWhat are metaclasses in Python?Finding the index of an item given a list containing it in PythonWhat is the difference between Python's list methods append and extend?How can I safely create a nested directory?Does Python have a ternary conditional operator?Convert bytes to a string?Does Python have a string 'contains' substring method?How do I lowercase a string in Python?Why is “1000000000000000 in range(1000000000000001)” so fast in Python 3?
What is the evidence on the danger of feeding whole blueberries and grapes to infants and toddlers?
How to translate 脑袋短路 into English?
How to avoid using System.String with Rfc2898DeriveBytes in C#
Does git delete empty folders?
Has any ancient or medieval Vedic scholar refuted the guna-based varna theory?
Why the color Red in Us, what is the significance?
Do predators tend to have vertical slit pupils versus horizontal for prey animals?
Metal that glows when near pieces of itself
Story that includes a description: "Two concentric circles, intersecting at three points"
How to think about joining a company whose business I do not understand?
Why didn’t Doctor Strange stay in the original winning timeline?
Unsolved Problems (Not Independent of ZFC) due to Lack of Computational Power
How does the Saturn V Dynamic Test Stand work?
E: Sub-process /usr/bin/dpkg returned an error code (1) - but how do I find the meaningful error messages in APT's output?
Chess software to analyze games
How can I train a replacement without letting my bosses and the replacement know?
Homogeneous Equations and Linear Algebra
Why do some academic journals requires a separate "summary" paragraph in addition to an abstract?
Can my Boyfriend, who lives in the UK and has a Polish passport, visit me in the USA?
Moons that can't see each other
How best to join tables, which have different lengths on the same column values which exist in both tables?
Can I submit a paper under an alias so as to avoid trouble in my country?
How can I override the serving of Media Files? (Implementing authentication for media items)
Do living authors still get paid royalties for their old work?
Is using Python f-strings effective for generating Python code?
Calling an external command in PythonWhat are metaclasses in Python?Finding the index of an item given a list containing it in PythonWhat is the difference between Python's list methods append and extend?How can I safely create a nested directory?Does Python have a ternary conditional operator?Convert bytes to a string?Does Python have a string 'contains' substring method?How do I lowercase a string in Python?Why is “1000000000000000 in range(1000000000000001)” so fast in Python 3?
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
I have not found any related questions or examples of Python code using f-strings to generate Python code. Is there an underlying problem that I should know about? f-strings are really convenient and seem to be rather efficient for my needs.
I am generating some python scripts that can be used in the command line for automatically processing folders with remote sensing images. I was going to manually write some files by hand but realized is was relatively easy to automate the process by externalizing metadata regarding the expressions.
Program logic:
- Extract expressions containing information on the different types of calculations that could be performed on the images (any sort of remote sensing indice)
- Iterate through expressions
- Create file with expression name (and other standards)
- Insert expression information into f-strings
- Write f-string to create file
I will also generate some tests automatically once settled on the method to be used. Is there a limit from which f-strings will not handle the code efficiently?
Some people have discussed using Python templates like Jinja2. However, if f-strings are sufficient I do not wish to integrate another external dependency.
from expressions_meta import expressions
for key in expressions.keys():
file_name = '_'.join([key, 'dir', 'cl.py'])
with open(file_name, 'w') as f:
f.write(f"""
import sys
import getopt
from gdal_dir_calc import GDALDirCalc
expression = expressions[key]
band_meta =
[...]
gdal_dir_obj.main()
""")
I might just be overly cautious but I think the topic could address other applications as well.
Any other tips regarding the use of f-strings for Python code generation or another tool?
python python-3.x code-generation
|
show 5 more comments
I have not found any related questions or examples of Python code using f-strings to generate Python code. Is there an underlying problem that I should know about? f-strings are really convenient and seem to be rather efficient for my needs.
I am generating some python scripts that can be used in the command line for automatically processing folders with remote sensing images. I was going to manually write some files by hand but realized is was relatively easy to automate the process by externalizing metadata regarding the expressions.
Program logic:
- Extract expressions containing information on the different types of calculations that could be performed on the images (any sort of remote sensing indice)
- Iterate through expressions
- Create file with expression name (and other standards)
- Insert expression information into f-strings
- Write f-string to create file
I will also generate some tests automatically once settled on the method to be used. Is there a limit from which f-strings will not handle the code efficiently?
Some people have discussed using Python templates like Jinja2. However, if f-strings are sufficient I do not wish to integrate another external dependency.
from expressions_meta import expressions
for key in expressions.keys():
file_name = '_'.join([key, 'dir', 'cl.py'])
with open(file_name, 'w') as f:
f.write(f"""
import sys
import getopt
from gdal_dir_calc import GDALDirCalc
expression = expressions[key]
band_meta =
[...]
gdal_dir_obj.main()
""")
I might just be overly cautious but I think the topic could address other applications as well.
Any other tips regarding the use of f-strings for Python code generation or another tool?
python python-3.x code-generation
3
Why do you even need many scripts with (potentially) almost exactly the same source code, rather than a single script that accepts input from CLI arguments or conf files?
– DeepSpace
Mar 27 at 14:45
Irrelevant to the question, but you do realize thatfile_namewill actually be overwritten on each of theexpressionsiterations, right? You'll end up with just the last value.
– Matias Cicero
Mar 27 at 14:46
@DeepSpace: The objective is to have specific indice calculators that can be easily used by people with little technical background. Like calculating an NDVI or NDSI and having only to pass the required and simplified arguments for the calculation.
– Zachary Deziel
Mar 27 at 14:52
@MatiasCicero: Yes, the program generates as many scripts as there are expressions.
– Zachary Deziel
Mar 27 at 14:54
@DeepSpace: To answer your questions more clearly, the script is based on gdal.org/gdal_calc.html. gdal_calc already provides a way to treat individual images in a general command line utility. The interest of my project is processing directories of images and having a more abstracted command line interface (having more explicit arguments than (A-B)/(A+B) for example).
– Zachary Deziel
Mar 27 at 15:08
|
show 5 more comments
I have not found any related questions or examples of Python code using f-strings to generate Python code. Is there an underlying problem that I should know about? f-strings are really convenient and seem to be rather efficient for my needs.
I am generating some python scripts that can be used in the command line for automatically processing folders with remote sensing images. I was going to manually write some files by hand but realized is was relatively easy to automate the process by externalizing metadata regarding the expressions.
Program logic:
- Extract expressions containing information on the different types of calculations that could be performed on the images (any sort of remote sensing indice)
- Iterate through expressions
- Create file with expression name (and other standards)
- Insert expression information into f-strings
- Write f-string to create file
I will also generate some tests automatically once settled on the method to be used. Is there a limit from which f-strings will not handle the code efficiently?
Some people have discussed using Python templates like Jinja2. However, if f-strings are sufficient I do not wish to integrate another external dependency.
from expressions_meta import expressions
for key in expressions.keys():
file_name = '_'.join([key, 'dir', 'cl.py'])
with open(file_name, 'w') as f:
f.write(f"""
import sys
import getopt
from gdal_dir_calc import GDALDirCalc
expression = expressions[key]
band_meta =
[...]
gdal_dir_obj.main()
""")
I might just be overly cautious but I think the topic could address other applications as well.
Any other tips regarding the use of f-strings for Python code generation or another tool?
python python-3.x code-generation
I have not found any related questions or examples of Python code using f-strings to generate Python code. Is there an underlying problem that I should know about? f-strings are really convenient and seem to be rather efficient for my needs.
I am generating some python scripts that can be used in the command line for automatically processing folders with remote sensing images. I was going to manually write some files by hand but realized is was relatively easy to automate the process by externalizing metadata regarding the expressions.
Program logic:
- Extract expressions containing information on the different types of calculations that could be performed on the images (any sort of remote sensing indice)
- Iterate through expressions
- Create file with expression name (and other standards)
- Insert expression information into f-strings
- Write f-string to create file
I will also generate some tests automatically once settled on the method to be used. Is there a limit from which f-strings will not handle the code efficiently?
Some people have discussed using Python templates like Jinja2. However, if f-strings are sufficient I do not wish to integrate another external dependency.
from expressions_meta import expressions
for key in expressions.keys():
file_name = '_'.join([key, 'dir', 'cl.py'])
with open(file_name, 'w') as f:
f.write(f"""
import sys
import getopt
from gdal_dir_calc import GDALDirCalc
expression = expressions[key]
band_meta =
[...]
gdal_dir_obj.main()
""")
I might just be overly cautious but I think the topic could address other applications as well.
Any other tips regarding the use of f-strings for Python code generation or another tool?
python python-3.x code-generation
python python-3.x code-generation
edited Mar 28 at 4:02
Nathan Vērzemnieks
4,6981 gold badge6 silver badges18 bronze badges
4,6981 gold badge6 silver badges18 bronze badges
asked Mar 27 at 14:40
Zachary DezielZachary Deziel
114 bronze badges
114 bronze badges
3
Why do you even need many scripts with (potentially) almost exactly the same source code, rather than a single script that accepts input from CLI arguments or conf files?
– DeepSpace
Mar 27 at 14:45
Irrelevant to the question, but you do realize thatfile_namewill actually be overwritten on each of theexpressionsiterations, right? You'll end up with just the last value.
– Matias Cicero
Mar 27 at 14:46
@DeepSpace: The objective is to have specific indice calculators that can be easily used by people with little technical background. Like calculating an NDVI or NDSI and having only to pass the required and simplified arguments for the calculation.
– Zachary Deziel
Mar 27 at 14:52
@MatiasCicero: Yes, the program generates as many scripts as there are expressions.
– Zachary Deziel
Mar 27 at 14:54
@DeepSpace: To answer your questions more clearly, the script is based on gdal.org/gdal_calc.html. gdal_calc already provides a way to treat individual images in a general command line utility. The interest of my project is processing directories of images and having a more abstracted command line interface (having more explicit arguments than (A-B)/(A+B) for example).
– Zachary Deziel
Mar 27 at 15:08
|
show 5 more comments
3
Why do you even need many scripts with (potentially) almost exactly the same source code, rather than a single script that accepts input from CLI arguments or conf files?
– DeepSpace
Mar 27 at 14:45
Irrelevant to the question, but you do realize thatfile_namewill actually be overwritten on each of theexpressionsiterations, right? You'll end up with just the last value.
– Matias Cicero
Mar 27 at 14:46
@DeepSpace: The objective is to have specific indice calculators that can be easily used by people with little technical background. Like calculating an NDVI or NDSI and having only to pass the required and simplified arguments for the calculation.
– Zachary Deziel
Mar 27 at 14:52
@MatiasCicero: Yes, the program generates as many scripts as there are expressions.
– Zachary Deziel
Mar 27 at 14:54
@DeepSpace: To answer your questions more clearly, the script is based on gdal.org/gdal_calc.html. gdal_calc already provides a way to treat individual images in a general command line utility. The interest of my project is processing directories of images and having a more abstracted command line interface (having more explicit arguments than (A-B)/(A+B) for example).
– Zachary Deziel
Mar 27 at 15:08
3
3
Why do you even need many scripts with (potentially) almost exactly the same source code, rather than a single script that accepts input from CLI arguments or conf files?
– DeepSpace
Mar 27 at 14:45
Why do you even need many scripts with (potentially) almost exactly the same source code, rather than a single script that accepts input from CLI arguments or conf files?
– DeepSpace
Mar 27 at 14:45
Irrelevant to the question, but you do realize that
file_name will actually be overwritten on each of the expressions iterations, right? You'll end up with just the last value.– Matias Cicero
Mar 27 at 14:46
Irrelevant to the question, but you do realize that
file_name will actually be overwritten on each of the expressions iterations, right? You'll end up with just the last value.– Matias Cicero
Mar 27 at 14:46
@DeepSpace: The objective is to have specific indice calculators that can be easily used by people with little technical background. Like calculating an NDVI or NDSI and having only to pass the required and simplified arguments for the calculation.
– Zachary Deziel
Mar 27 at 14:52
@DeepSpace: The objective is to have specific indice calculators that can be easily used by people with little technical background. Like calculating an NDVI or NDSI and having only to pass the required and simplified arguments for the calculation.
– Zachary Deziel
Mar 27 at 14:52
@MatiasCicero: Yes, the program generates as many scripts as there are expressions.
– Zachary Deziel
Mar 27 at 14:54
@MatiasCicero: Yes, the program generates as many scripts as there are expressions.
– Zachary Deziel
Mar 27 at 14:54
@DeepSpace: To answer your questions more clearly, the script is based on gdal.org/gdal_calc.html. gdal_calc already provides a way to treat individual images in a general command line utility. The interest of my project is processing directories of images and having a more abstracted command line interface (having more explicit arguments than (A-B)/(A+B) for example).
– Zachary Deziel
Mar 27 at 15:08
@DeepSpace: To answer your questions more clearly, the script is based on gdal.org/gdal_calc.html. gdal_calc already provides a way to treat individual images in a general command line utility. The interest of my project is processing directories of images and having a more abstracted command line interface (having more explicit arguments than (A-B)/(A+B) for example).
– Zachary Deziel
Mar 27 at 15:08
|
show 5 more comments
1 Answer
1
active
oldest
votes
If you are coming across this question, be sure to review the design of your program.
Most likely you are trying to implement a solution in which you violate DRY principles.
For command line applications:
Instead of generating many specific commands, look into to passing a name argument which in turn can be used with a selection of arguments.
From the standard library, some tools that may be helpful are configparser, shlex, cmd, getopt and argparse. See the standard library documentation on these tools.
Click is an interesting third party package.
Thanks @SergeBallesta for your helpful comments.
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55379934%2fis-using-python-f-strings-effective-for-generating-python-code%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
If you are coming across this question, be sure to review the design of your program.
Most likely you are trying to implement a solution in which you violate DRY principles.
For command line applications:
Instead of generating many specific commands, look into to passing a name argument which in turn can be used with a selection of arguments.
From the standard library, some tools that may be helpful are configparser, shlex, cmd, getopt and argparse. See the standard library documentation on these tools.
Click is an interesting third party package.
Thanks @SergeBallesta for your helpful comments.
add a comment |
If you are coming across this question, be sure to review the design of your program.
Most likely you are trying to implement a solution in which you violate DRY principles.
For command line applications:
Instead of generating many specific commands, look into to passing a name argument which in turn can be used with a selection of arguments.
From the standard library, some tools that may be helpful are configparser, shlex, cmd, getopt and argparse. See the standard library documentation on these tools.
Click is an interesting third party package.
Thanks @SergeBallesta for your helpful comments.
add a comment |
If you are coming across this question, be sure to review the design of your program.
Most likely you are trying to implement a solution in which you violate DRY principles.
For command line applications:
Instead of generating many specific commands, look into to passing a name argument which in turn can be used with a selection of arguments.
From the standard library, some tools that may be helpful are configparser, shlex, cmd, getopt and argparse. See the standard library documentation on these tools.
Click is an interesting third party package.
Thanks @SergeBallesta for your helpful comments.
If you are coming across this question, be sure to review the design of your program.
Most likely you are trying to implement a solution in which you violate DRY principles.
For command line applications:
Instead of generating many specific commands, look into to passing a name argument which in turn can be used with a selection of arguments.
From the standard library, some tools that may be helpful are configparser, shlex, cmd, getopt and argparse. See the standard library documentation on these tools.
Click is an interesting third party package.
Thanks @SergeBallesta for your helpful comments.
answered Mar 27 at 16:37
Zachary DezielZachary Deziel
114 bronze badges
114 bronze badges
add a comment |
add a comment |
Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.
Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55379934%2fis-using-python-f-strings-effective-for-generating-python-code%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
3
Why do you even need many scripts with (potentially) almost exactly the same source code, rather than a single script that accepts input from CLI arguments or conf files?
– DeepSpace
Mar 27 at 14:45
Irrelevant to the question, but you do realize that
file_namewill actually be overwritten on each of theexpressionsiterations, right? You'll end up with just the last value.– Matias Cicero
Mar 27 at 14:46
@DeepSpace: The objective is to have specific indice calculators that can be easily used by people with little technical background. Like calculating an NDVI or NDSI and having only to pass the required and simplified arguments for the calculation.
– Zachary Deziel
Mar 27 at 14:52
@MatiasCicero: Yes, the program generates as many scripts as there are expressions.
– Zachary Deziel
Mar 27 at 14:54
@DeepSpace: To answer your questions more clearly, the script is based on gdal.org/gdal_calc.html. gdal_calc already provides a way to treat individual images in a general command line utility. The interest of my project is processing directories of images and having a more abstracted command line interface (having more explicit arguments than (A-B)/(A+B) for example).
– Zachary Deziel
Mar 27 at 15:08