I'm trying to make this work on XAMPP. It works fine on a Linux server/virtual machine.
I need to send an associative array to a python script, and I do it with:
<?php
echo "Test simple call/answer process<br>";
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
$param = base64_encode(json_encode($age));
$command = escapeshellcmd('python python_array_answer.py $param');
$output = shell_exec($command);
$obj = json_decode($output);
print_r($obj);
?>
The Python script is:
#! /Users/.../AppData/Local/Programs/Python/Python37/python.exe
import sys
import json
import base64
hotel_data = json.loads(base64.b64decode(sys.argv[1]))
print(json.dumps(hotel_data))
I get a NULL array back, with this error:
Traceback (most recent call last):
File "python_array_answer.py", line 6, in <module>
hotel_data = json.loads(base64.b64decode(sys.argv[1]))
File "C:\Users\mghiglia\AppData\Local\Programs\Python\Python37\lib\base64.py", line 87, in b64decode
return binascii.a2b_base64(s)
binascii.Error: Invalid base64-encoded string: number of data characters (5) cannot be 1 more than a multiple of 4
Any ideas? thank.
Assuming the rest of the code is okay, you're using single quotes in this line
$command = escapeshellcmd('python python_array_answer.py $param');
where you should either use double quotes, so php known to replace $param with the value of variable $param, or concatenate the two like this...
$command = escapeshellcmd('python python_array_answer.py '.$param);
Related
I run my bash script my_file.sh in a python file as follows:
import subprocess
def rest_api():
params = {
'query': 'indepedence day',
'formats': '["NEWSPAPER"]',
}
subprocess.call(['bash',
'my_file.sh',
f'QUERY={params.get("query")}',
f'DOC_TYPE={params.get("formats")}',
f'LANGUAGE={params.get("lang")}', # returns None!
])
if __name__ == '__main__':
rest_api()
Several of my input arguments in subprocess.call do not normally exist in a dictionary params={} (here I provided f'LANGUAGE={params.get("lang")}' as one example). I handle such unavailability in my_file.sh to initialize with something, for instance:
if [ -z "$LANGUAGE" ]; then LANGUAGE="${LANGUAGE:-[]}"; fi
What I want is to apply some sort of if else statement in subprocess.call function with this logic:
if params.get("lang") is None, do not even send it as an input to bash file, e.g., treat it as I never provided such input for my_file.sh.
Therefore, I tried to rewrote my code like this:
subprocess.call(['bash',
'my_file.sh',
f'QUERY={params.get("query")}',
f'DOC_TYPE={params.get("formats")}',
if params.get("lang"): f'LANGUAGE={params.get("lang")}', # syntax Error
])
which is wrong I get the following invalid syntax error:
Traceback (most recent call last):
File "nationalbiblioteket_logs.py", line 13, in <module>
from url_scraping import *
File "/home/xenial/WS_Farid/DARIAH-FI/url_scraping.py", line 17, in <module>
from utils import *
File "/home/xenial/WS_Farid/DARIAH-FI/utils.py", line 53
if params.get("lang"): f'LANGUAGE={params.get("lang")}',
^
SyntaxError: invalid syntax
Do I have a wrong understanding of applying if else statement for the input arguments of a python function or is there an easier or cleaner way doing it?
Cheers,
You can specify the default when calling .get(), so use an empty string.
f'LANGUAGE={params.get("lang", "")}'
If you don't want the LANGUAGE= argument at all when no value is provided, you need to build the list dynamically.
cmd = ['bash',
'my_file.sh',
f'QUERY={params.get("query")}',
f'DOC_TYPE={params.get("formats")}']
if (lang := params.get("lang")) is not None:
cmd += [f'LANGUAGE={lang}']
subprocess.call(cmd)
I'm trying to bring on my local server (XAMPP), a script that's working on my VPS server (Linux CentOS7).
On XAMPP, I call the Python script wit PHP, something like:
$hotel = array("Name"=>$_POST["NAME"]
,..
);
$param = escapeshellcmd(base64_encode(json_encode($hotel)));
$result = shell_exec('python C:\xampp\htdocs\bounce.py $param');
$obj = json_decode($result);
The Python script is something like:
#! /Users/<user>/AppData/Local/Programs/Python/Python37/python.exe
import sys
import json
import base64
content = json.loads(base64.b64decode(sys.argv[1]))
print(json.dumps(content))
The returned JSON string is NULL
This is the Apache error:
[php:warn] [pid 11176:tid 1884] [client ::1:55182] PHP Warning: Attempt to read property "Name" on null in C:\\xampp\\htdocs\\hotel_results.php on line 46, referer: http://localhost/
Updated Django with no results
If the problem is caused by not reading the "$param" variable due to single quotes, replacing the line of
$result = shell_exec('python C:\xampp\htdocs\bounce.py $param');
with
$result = shell_exec("python C:\\xampp\\htdocs\\bounce.py $param");
could help. worth a try.
I have a script, let's call it /home/pi/somescript.py and when I call it with /bin/python3.7 /home/pi/somescript.py everything works as it should.
Now I'm trying to call from a php script with exec('/bin/python3.7 /home/pi/somescript.py', $output, $ret_code);. This however throws a ModuleNotFoundError.
But when I run the interactive PHP shell and paste the above exec in there, it also works. Am I missing something? What could be the cause of this? How do I fix this?
The relevant part of the python script:
import sys
sys.stderr = sys.stdout # so I get the stacktrace in the $output of the php file
from iso3166 import countries # <- error here
# ...
I'm running a lighttpd server. The PHP file lies in /var/www/html/info.php and I access it via a browser with http://raspberrypi:8080/info.php
The relevant part of the PHP file:
exec('/bin/python3.7 /home/pi/somescript.py', $output, $ret_code);
$data = ["out" => $output];
header('Content-Type: application/json');
echo json_encode($data);
// this way I get the output when in the browser
The stacktrace I get:
Traceback (most recent call last):
File "/home/pi/somescript.py", line 6, in <module>
from iso3166 import countries
ModuleNotFoundError: No module named 'iso3166'
I trying to read dicom file with python3 and pydicom library. For some dicom data, I can't get data correctly and get error messages when I tried to print the result of pydicom.dcmread.
However, I have tried to use python2 and it worked well. I checked out the meta information and compared it with other dicom files which can be processed, I didn't find any difference between them.
import pydiom
ds = pydicom.dcmread("xxxxx.dicom")
print(ds)
Traceback (most recent call last):
File "generate_train_data.py", line 387, in <module>
tf.app.run()
File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/platform/app.py", line 125, in run
_sys.exit(main(argv))
File "generate_train_data.py", line 371, in main
create_ann()
File "generate_train_data.py", line 368, in create_ann
ds_ann_dir, case_name, merge_channel=False)
File "generate_train_data.py", line 290, in process_dcm_set
all_dcms, dcm_truth_infos = convert_dicoms(dcm_list, zs)
File "generate_train_data.py", line 179, in convert_dicoms
instance_num, pixel_spacing, img_np = extract_info(dcm_path)
File "generate_train_data.py", line 147, in extract_info
print(ds)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 2277-2279: ordinal not in range(128)
Anyone has come across the same problem?
Can you give an example for such a dicom file? When running the pydicom example with python 3.7 it's working perfectly:
import matplotlib.pyplot as plt
import pydicom
from pydicom.data import get_testdata_files
filename = get_testdata_files("CT_small.dcm")[0]
ds = pydicom.dcmread(filename)
plt.imshow(ds.pixel_array, cmap=plt.cm.bone)
It's also working with the sample dicom files from the Medical Image Samples.
I believe the cause of the problem is that Python (for me it only happened in Python 3 running on Centos 7.6 Linux printing to a terminal window on MacOS) is not able to figure out how to print a string that contains a non-ascii character because of the setting of the locale. You can use the locale command to see the results. Mine started out with everything set to "C". I set the LANG environment variable to en_US.UTF-8. With that setting it worked for me.
In csh this is done using
setenv LANG en_US.UTF-8
In bash use:
export LANG=en_US.UTF-8
My problem resulted from having 'ยต' in the Series Description element. The file was an attenuation map from a SPECT reconstruction on a Siemens scanner. I used the following Python code to help figure out the problem.
#! /usr/bin/env python3
import pydicom as dicom
from sys import exit, argv
def myprint(ds, indent=0):
"""Go through all items in the dataset and print them with custom format
Modelled after Dataset._pretty_str()
"""
dont_print = ['Pixel Data', 'File Meta Information Version']
indent_string = " " * indent
next_indent_string = " " * (indent + 1)
for data_element in ds:
if data_element.VR == "SQ": # a sequence
print(indent_string, data_element.name)
for sequence_item in data_element.value:
myprint(sequence_item, indent + 1)
print(next_indent_string + "---------")
else:
if data_element.name in dont_print:
print("""<item not printed -- in the "don't print" list>""")
else:
repr_value = repr(data_element.value)
if len(repr_value) > 50:
repr_value = repr_value[:50] + "..."
try:
print("{0:s} {1:s} = {2:s}".format(indent_string,
data_element.name,
repr_value))
except:
print(data_element.name,'****Error printing value')
for f in argv[1:]:
ds = dicom.dcmread(f)
myprint(ds, indent=1)
This is based on the myprint function from]1
The code tries to print out all the data items. It catches exceptions and prints "****Error printing value" when there is an error.
I am working on managing Canonical CM Landscape through Python api's. I don't know if any one could help me but am stuck in one point and I don't know if it is a simple Python error of that specific library. This is part of larger script but it drops when I tried to use the last function in this listing.
import os, json, sys, subprocess, csv, datetime, time
from landscape_api.base import API, HTTPError
from subprocess import Popen,PIPE,STDOUT,call
uri = "xxxxxxxxxxxxxxxxxxxxxxxx"
key = "xxxxxxxxxxxxxxxxxxxx"
secret = "xxxxxxxxxxxxxxxxxxxxxxx"
api = API(uri, key, secret)
proc=Popen('zenity --entry --text "Fill with machine Tag to be searched" --entry- text "Type Tag"', shell=True, stdout=PIPE, ) #Input from zenity window
output=proc.communicate()[0]
user="root"
script="2408"
mac = api.execute_script(query="tag:%s", script_id="script_id:%s", username="user:%s" %(output, script, user))
Last function api.execute_script returns error
Traceback (most recent call last):
File "Python_MAC_IP.py", line 35, in <module>
mac = api.execute_script(query="tag:%s", script_id="script_id:%s", username="user:%s" %(output, script, user))
TypeError: not all arguments converted during string formatting
You can only use the % operator on a single string, not across multiple strings. What you are currently asking Python to do is insert multiple variables into a string that only has one defined.
Change this line:
mac = api.execute_script(query="tag:%s", script_id="script_id:%s", username="user:%s" %(output, script, user))
to this:
mac = api.execute_script(query="tag:%s" %tag, script_id="script_id:%s" %script, username="user:%s" %user