I wish to neatly display the output of a python file after it has run some commands in the command prompt.
Currently, a part of my PHP code looks like this:
$output2 = shell_exec('python amassprocess.py 2>&1' . $asnum);
echo $output2
It basically sends the user input to the python file amassprocess.py and runs the file with the user input.
The amassprocess.py file looks like this currently:
import os, sys
#asnum = sys.argv[1]
asnum = "46489"
print("Here is a list of top level seed domain related to the AS Number provided:")
topdomain = os.system('cmd /c "amass.exe intel -asn {}"'.format(asnum))
for i in topdomain:
print(i)
print("<br>")
PS: ignore the 2 asnum, one of them is for testing
The resulting output from running the python script is this:
Here is a list of top level seed domain related to the AS Number provided:
ttvnw.net
justin.tv
twitch.tv
socialcam.com
Traceback (most recent call last):
File "z:/xampp/htdocs/majorproject/amassprocess.py", line 8, in <module>
for i in topdomain:
TypeError: 'int' object is not iterable
However, what i hope the output to be when i run the python script is as follows:
Here is a list of top level seed domain related to the AS Number provided:
ttvnw.net
<br>
justin.tv
<br>
twitch.tv
<br>
socialcam.com
This so that when it is displayed in PHP, it looks like this:
Here is a list of top level seed domain related to the AS Number provided:
ttvnw.net
justin.tv
twitch.tv
socialcam.com
Currently in PHP, the result are all just displayed in a single line like so:
ttvnw.net justin.tv twitch.tv twitchcon.com socialcam.com Traceback (most recent call last): File "amassprocess.py", line 7, in for i in topdomain: TypeError: 'int' object is not iterable
I would be grateful for any help or ideas. Thank you.
Using your code, you can replace newlines with <br />:
$output2 = shell_exec('python amassprocess.py 2>&1' . $asnum);
echo nl2br($output2);
Or you can get an array of lines and join on <br />::
exec('python amassprocess.py 2>&1' . $asnum, $output2);
echo implode('<br />', $output2);
Alternately, with your code, you can display in <pre> or maybe <code> tags, which browsers will render pre-formatted with newlines, tabs etc:
$output2 = shell_exec('python amassprocess.py 2>&1' . $asnum);
echo "<pre>$output2</pre>";
you can do the following in your python code.
define one variable to hold like x="<br>"
and then use for output print(i+x) this will concatenate your string.
Related
I am Following Chris P's 'Visualize Real-world JSON Data in Blender (3D Chart Animation Nodes Tutorial)' on YouTube but I seem to have got stuck at the first hurdle of importing the data. I have followed his instructions completely and am unsure why the script keeps failing. I have attached his script, My script, my file location, my error message and a snap shot of his video. I am On windows OS, he is on Linux I'menter image description here not sure if that makes a difference. Here is the link to the video: https://www.youtube.com/watch?v=0aRjInmibSw&t=1055s THE TIMESTAMP FOR HIS CODE IS 6 min.
FILE NAME: Export.json
MY FILE LOCATION: C:\Users\Jordan\Downloads
MY CODE
import json
with open(r'C:/Users/Jordan/Downloads/Export.json','r') as f:
j=json.load(f)
print (j)
MY ERROR MESSAGE:
Traceback (most recent call last):
File "D:\Mixed Graphs\Blender json\3D Charts.blend\My Script", line 3, in <module>
OSError: [Errno 22] Invalid argument: '/C:/Users/Jordan/Downloads/Export'
Error: Python script failed, check the message in the system console
HIS CODE:
import json
with open('/Home/chris/downloads/tutorial1.json') as f:
json.load(f)
print (j)
Your problem seems to be that you're using "/"(slash) instead of ""(backslash) on Windows.
In addition you need to use two "\" as one backslash signals an escaping for the next character.
Fix therefore should be:
import json
with open(r'C:\\Users\\Jordan\\Downloads\\Export.json','r') as f:
j=json.load(f)
print (j)
I need to get a list of all albums of my YouTube Music uploads library with ytmusicapi and I never work with Python before. I created the headers_auth.json and a test.py file with the following code from the example:
from ytmusicapi import YTMusic
ytmusic = YTMusic('headers_auth.json')
playlistId = ytmusic.create_playlist("test", "test description")
search_results = ytmusic.search("Oasis Wonderwall")
ytmusic.add_playlist_items(playlistId, [search_results[0]['videoId']])
I ran from the Ubuntu terminal: python /home/do/Desktop/ytmusicapi/ytmusicapi-master/test.py
Result error:
Traceback (most recent call last): File
"/home/do/Desktop/ytmusicapi/ytmusicapi-master/test.py", line 1, in
from ytmusicapi import YTMusic File "/home/do/Desktop/ytmusicapi/ytmusicapi-master/ytmusicapi/init.py",
line 2, in
from ytmusicapi.ytmusic import YTMusic File "/home/do/Desktop/ytmusicapi/ytmusicapi-master/ytmusicapi/ytmusic.py",
line 28
auth: str = None,
^ SyntaxError: invalid syntax
How to fix that?
This is because you are using a different version of Python.
The library you are using requires Python>=3.5 wheraas you seem to be using Python2.
If you are curious this code
def f(x:int):
return
is valid in Python3.5+ versions but not in Python2.
You will have to either switch to Python3 to use that library or else you can clone the repo and convert the whole repo to Python2 using something like this(though there might be other ways too).
I'd recommend you simply switch to Python3.5 or higher.
Let me first start this off by stating that I am a complete beginner to coding and my attempts to fix this have been limited. I am trying to follow this Arduino controlled piano robot. It takes a textified midi file and uses python to translate it into 8-bit. The code is attached near the bottom of the link, I had some formatting issues when placing it here.
This link to the textified midi file used. before running the code I changed the input_file = open to text file path like so,
input_file = open("C:\\Users\\nby20\\Downloads\\megalovania.txt")
After running the code I get a text output file as expected however it is blank and I get a few errors:
Traceback (most recent call last):
File "C:\Users\nby20\Downloads\python_code_for_translation.py", line 184, in <module>
main()
File "C:\Users\nby20\Downloads\python_code_for_translation.py", line 23, in main
result[-1] = str(temp_time) + "," + set_bit_prev(on_off_finder(a), note_finder(a), -1)
File "C:\Users\nby20\Downloads\python_code_for_translation.py", line 178, in on_off_finder
end = in_string.index("ch=") - 1
ValueError: substring not found
Any suggestions on how to fix this would be greatly appreciated.
The Traceback is like debugging information you can use to trace which functions were called when the error was thrown. It seems the error occurred when it was executing this bit of conditional logic, lines 22-23, of the main function:
elif time_finder_comm(result[-1]) == temp_time:
result[-1] = str(temp_time) + "," + set_bit_prev(on_off_finder(a), note_finder(a), -1)
which called the on_off_finder function which just tries to figure out if the line says 'On' or 'Off'.
It seems the file reader only expects lines like this:
55248 Off ch=10 n=40 v=64
However, in the file you uploaded, there also lines like this:
55248 Meta TrkEnd
TrkEnd
The index function throws ValueError: substring not found if the substring passed in does not exist in the string, which in this case (line 178 below) is the string "ch":
end = in_string.index("ch=") - 1
Try removing those kind of lines and re-run the script? Find all lines with "Trk" and and remove them, or make 3 separate files because there seem to be 3 blocks of lines in 'megalovania.txt' that will trip up the script:
(starting at line 2469):
55248 Meta TrkEnd
TrkEnd
MTrk
...
(starting at line 4071):
58368 Meta TrkEnd
TrkEnd
MTrk
...
(starting at line 6431):
55296 Meta TrkEnd
TrkEnd
I want to search a Perforce depot for files.
I do this from a python script and use the p4python library command:
list = p4.run("files", "//mypath/myfolder/*")
This works fine as long as myfolder contains some files. I get a python list as a return value. But when there is no file in myfolder the program stops running and no error message is displayed. My goal is to get an empty python list, so that I can see that this folder doesn't contain any files.
Does anybody has some ideas? I could not find information in the p4 files documentation and on StackOverflow.
I'm going to guess you've got an exception handler around that command execution that's eating the exception and exiting. I wrote a very simple test script and got this:
C:\Perforce\test>C:\users\samwise\AppData\local\programs\python\Python36-32\python files.py
Traceback (most recent call last):
File "files.py", line 6, in <module>
print(p4.run("files", "//depot/no such path/*"))
File "C:\users\samwise\AppData\local\programs\python\Python36-32\lib\site-packages\P4.py", line 611, in run
raise e
File "C:\users\samwise\AppData\local\programs\python\Python36-32\lib\site-packages\P4.py", line 605, in run
result = P4API.P4Adapter.run(self, *flatArgs)
P4.P4Exception: [P4#run] Errors during command execution( "p4 files //depot/no such path/*" )
[Error]: "//depot/no such path/* - must refer to client 'Samwise-dvcs-1509687817'."
Try something like this ?
import os
if len(os.listdir('//mypath/myfolder/') ) == 0: # Do not execute p4.run if directory is empty
list = []
else:
list = p4.run("files", "//mypath/myfolder/*")
I'm trying to pass an array from bash to python using the old getenv method however I keep getting this error:
./crcFiles.sh: line 7: export: `0021': not a valid identifier
Traceback (most recent call last):
File "/shares/web/vm3618/optiload/prog/legalLitres.py", line 30, in <module>
for i in mdcArray.split(' '):
AttributeError: 'NoneType' object has no attribute 'split'
could someone please explain why the $mdcNo isn't passing from bash to python successfully?
Code .sh:
#!/bin/bash
mdcNo=('0021' '0022' '0036' '0055' '0057' '0059' '0061' '0062' '0063' '0065' '0066' '0086' '0095' '0098' '0106' '0110' '0113' '0114' '0115' '0121' '0126' '0128' '0135' '0141' '0143' '0153' '0155' '0158')
localDIR=/shares/web/vm3618/optiload/prog
export mdcNo
$localDIR/legalLitres.py
for i in "${mdcNo[#]}"
do
echo $i
cp $localDIR/MDC$i/*/QqTrkRec.txt $localDIR/crccalc/.
cd $localDIR/crccalc
./crccalc.py QqTrkRec.txt
cp $localDIR/crccalc/QqTrkRec.txt $localDIR/MDC$i/.
done
code .py:
#!/usr/bin/python
import glob
import os
mdcArray = os.getenv('mdcNo')
#Legal Litres that hex and decimal
legalLitresHex = "47E0"
legalLitresTxt = '18,400'
# file name and Legal Litres header
legalHeader = ":00F0:"
hexFile = "QqTrkRec.txt"
# insert comment to explain change
comment = "#\n# 2015 Nov 20: Legal Litres changed to 18,400\n#\n"
commentFlag0 = "# SetDATA"
commentFlag1 = "# SetDATA"
try:
for i in mdcArray.split(' '):
line = ""
Qqfile = glob.glob("/shares/web/vm3618/optiload/prog/MDC"+i+"/*/"+hexFile)
outFile = Qqfile[0]+".new"
print i
If you want to pass a shell array to the Python script, your best bet is to do so as command line arguments. If you run the Python script like this:
python code.py "${mdcNo[#]}"
... then the Python code can just loop over sys.argv, which is always a list. (Specifically, the passed-in array will be the slice sys.argv[1:], since sys.argv[0] is always set to the name of the script itself.)
You were attempting to pass it in through the environment; the problem there is that the environment is a one-dimensional array of strings, with no support for arrays. If the command line is not an option and you have no choice but to use the environment, you'll have to set the environment variable to a string with some delimiter between elements, and split it inside the Python code. The bash for that case would look something like this:
export mdcList='0021,0022,0036,0055,0057,0059,0061,0062,0063,0065,0066,0086,0095,0098,0106,0110,0113,0114,0115,0121,0126,0128,0135,0141,0143,0153,0155,0158'
Or if you already have a bash array, you can build the strong from it:
export mdcList=${mdcNo[0]}
for i in "${mdcNo[#]:1}"; do
mdcList+=,$i
done
Either way, the Python script can recover the array as a list like this:
mdc_no = os.getenv('mdcList').split(',')
If your array elements aren't just numbers, you can replace the comma with something less likely to show up inside an element value; the traditional choice would be the ASCII Unit Separator (U+001F, $'\x1f' in Bash, '\x1f' in Python).
I think Mark Reed already gave you a very good explanation and solution.
Nevertheless, have you considered using python's argparse?
#!/usr/bin/env python
import argparse
def main():
parser = argparse.ArgumentParser()
parser.add_argument('stuff', nargs='+')
args = parser.parse_args()
print args.stuff
if __name__ == '__main__':
main()
Use:
$ mdcNo=('0021' '0022' '0036' '0055' '0057' '0059' '0061' '0062' '0063' '0065' '0066' '0086' '0095' '0098' '0106' '0110' '0113' '0114' '0115' '0121' '0126' '0128' '0135' '0141' '0143' '0153' '0155' '0158')
$ python argp.py "${mdcNo[#]}"
['0021', '0022', '0036', '0055', '0057', '0059', '0061', '0062', '0063', '0065', '0066', '0086', '0095', '0098', '0106', '0110', '0113', '0114', '0115', '0121', '0126', '0128', '0135', '0141', '0143', '0153', '0155', '0158']