How do I pass an array of strings to a python script as an argument?

2024/10/5 15:16:31

I've written a swift app that outputs an array of strings.

I would like to import this array into a python script for further processing into an excel file via xlsxwriter, I would like to do this as an argument.

My array looks like this:

[["1", "12:32", "Harry\'s\na wizard", "", ""], ["2", "12:34", "Harry reads a sign:", "Sign:", "\"You're a wizard Harry\""]]

I'd like to pass this into python verbatim, so I can process it into an excel table. The output is a human readable file.

I've tried adding my array into PyChars's "Modify Run Configuration...", then processing it via:

import sys
arr = sys.argv[1]
print(arr)

but I get: [[1,

I try to add the argument as """argument""", but I get: [[1, 12:32, Harry's\na

I try as: f"""argument""", but get: f[[1, 12:32, Harry's\na

f'argument' results in: f'[[1,

I try reading the argument with:

arr = ast.literal_eval(sys.argv)

but I get several errors ending in: "ValueError: malformed node or string: ..."

arr = ast.literal_eval(sys.argv[1])

gives me: return compile(source, filename, mode, flags, File "", line 1 [[1, ^ SyntaxError: unexpected EOF while parsing

I've solved this problem by exporting the array to a JSON file from my swift app and importing it in the python script, but I'd really like to know if there's any way of passing it as a command line argument.

Answer

You need to quote the argument in the shell to make it treat it as a single argument. And since the argument contains embedded quotes, you need to escape them, as well as the embedded backslash characters.

You'd also need to escape any $ or ` characters if they existed, since they also have meaning in double-quoted strings.

python testargv.py "[[\"1\", \"12:32\", \"Harry's\\na wizard\", \"\", \"\"], [\"2\", \"12:34\", \"Harry reads a sign:\", \"Sign:\", \"\\\"You're a wizard Harry\\\"\"]]"

Then use ast.literal_eval(sys.argv[1]) in the script to convert this to a list.

You can't use single quotes around the whole argument, because it doesn't support escaping of embedded single quotes. Another way to avoid all this escaping hell is to switch between single and double-quoted strings. Wrap most of it in single quotes, but use "'" for the embedded single quotes.

python testargv.py '[["1", "12:32", "Harry'"'"'s\na wizard", "", ""], ["2", "12:34", "Harry reads a sign:", "Sign:", "\"You'"'"'re a wizard Harry\""]]'
https://en.xdnf.cn/q/119591.html

Related Q&A

Match values of different dataframes

This dataframe is the principal with the original tweets. "original_ds_.csv" id tweet --------------------------------------------- 78 "onetoone"…

EOF while parsing

def main():NUMBER_OF_DAYS = 10NUMBER_OF_HOURS = 24data = []for i in range(NUMBER_OF_DAYS):data.append([])for j in range(NUMBER_OF_HOURS):data[i].append([])data[i][j].append(0)data[i][j].append(0)for k …

Why is bool(x) where x is any integer equal to True

I expected bool(1) to equate to True using Python - it does - then I expected other integers to error when converted to bool but that doesnt seem to be the case:>>> x=23 #<-- replace with a…

Getting TypeError while fetching value from table using Python and Django

I am getting error while fetching value from table using Python and Django. The error is below:Exception Type: TypeError Exception Value: not all arguments converted during string formattingMy code…

ValueError: The view **** didnt return an HttpResponse object. It returned None instead

Im using Django forms to handle user input for some point on my Django app. but it keeps showing this error whenever the user tries to submit the form. ValueError: The view *my view name goes here* di…

Game Development in Python, ruby or LUA? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, argum…

Problem with this error: (-215:Assertion failed) !ssize.empty() in function cv::resize OpenCV

I got stuck with this error after running resize function line: import cv2 import numpy as np import matplotlib.pyplot as pltnet = cv2.dnn.readNetFromDarknet(yolov3_custom.cfg, yolov3_custom_last.weigh…

When I run it tells me this : NameError: name lock is not defined?

• Assume that you have an array (data=[]) containing 500,000 elements and that each element has been assigned a random value between 1 and 10 (random.randint(1,10)) .for i in range (500000):data[i]…

Unable to find null bytes in Python code in Pycharm?

During copy/pasting code I often get null bytes in Python code. Python itself reports general error against module and doesnt specify location of null byte. IDE of my choice like PyCharm, doesnt have c…

remove single quotes in list, split string avoiding the quotes

Is it possible to split a string and to avoid the quotes(single)? I would like to remove the single quotes from a list(keep the list, strings and floats inside:l=[1,2,3,4.5]desired output:l=[1, 2, 3, …