I had almost finished on a software i was working on that should have worked but didn't. The software was intended to do the following:
Download a python script from the internet.
Automatically run it with the argument provided for the downloaded
file
But an unusual error occurred in the process of running the downloaded script.
python netscript.py [URL FOR TARGET FILE] [ARGUMENTS FOR TARGET FILE|
Error:
File "temp_dl/431341022.py", line 146
^
IndentationError: expected an indented block
Code:
from bs4 import BeautifulSoup
from subprocess import call
from sys import argv
import urllib2
import random
import os
script, url, ns_dledscript_arg = argv
def ns_runscript(ns_randfn, ns_dledscript_arg):
print "Running downloaded content..."
os.system("python temp_dl/%s.py %s" % (ns_randfn, ns_dledscript_arg))
def ns_getcontent(url, ns_dledscript_arg):
print "Getting content..."
ns_openurl = urllib2.urlopen(url).read()
print "Filtering content..."
#ns_filtered_data = re.sub( r'<[^>]*>', ' ', ns_openurl).strip()
ns_filtered_data = BeautifulSoup(ns_openurl, "html.parser")
ns_randfn = random.randrange(100000000, 999999999)
file = open("temp_dl/%s.py" % (ns_randfn), "w") #Create writable file with random name.
file.write("""%s""" % (ns_filtered_data)) #writes pretty code into the file with the random name.
ns_question_viewdata = raw_input("Do you want to print data on console? 'y' or 'n': ")
ns_runscript(ns_randfn, ns_dledscript_arg)
if ns_question_viewdata == 'y':
print ns_filtered_data
elif ns_question_viewdata == 'n':
exit()
else:
exit()
ns_getcontent(url, ns_dledscript_arg)
Related
I have the following problem
import os
import json
import wmi
from random import choice
import time
filename = "kill.json"
with open(filename) as file:
kill = json.load(file)
def taskKill(imageNames: list):
cmdPrefix = 'taskkill /F /IM '
for imageName in imageNames:
cmd = cmdPrefix + imageName
os.system(cmd)
while 1==1:
c=wmi.WMI()
def check_process_running(rty):
if(c.Win32_Process(name=rty)):
print("Process is running")
taskKill(kill)
return
else:
print("Process is not running")
StrA =choice(kill)
check_process_running(StrA)
In this code that detects if the program is open and closes it, no matter how I change it, it always says Process is not running.
The output of your script is depending on the line if(c.Win32_Process(name=rty)) - it seems the return of Win32_Process is always True.
Insert a print statement with the value of Win32_Process before this line
Have you tried to provide the argument as a String ("StrA" instead of StrA)?
To check all current running processes, use:
import os, wmi
c = wmi.WMI()
for process in c.Win32_Process(name="python.exe"):
print(process.ProcessId, process.Name)
print("current processId:", os.getpid())
I am running a main script on windows 10 that calls another script called audioplayer.py using the subprocess module in python.
I want to send some input arguments when calling the audioplayer.py. So I wrote the main script as follows:
The following is the main script:
from subprocess import call
call(["python", "C:/Users/Jeff/Documents/audioplayer.py", "hey.wav"])
The following is my audioplayer.py:
"""OpenAL playback example."""
import os, sys, time
from openal.audio import SoundSink, SoundSource
from openal.loaders import load_wav_file
if len (sys.argv) < 2:
print ("Usage: %s wavefile" % os.path.basename(sys.argv[0]))
print (" Using an example wav file...")
dirname = os.path.dirname(__file__)
fname = os.path.join(dirname, "default.wav")
else:
fname = sys.argv[1]
sink = SoundSink()
sink.activate()
source = SoundSource(position=[10, 0, 0])
source.looping = True
data = load_wav_file(fname)
source.queue(data)
sink.play(source)
source.position = [source.position[0], source.position[1], source.position[2]]
sink.update()
time.sleep(2)
print("playing at %r" % source.position)
But I keep getting the following error even though the file does exist in the same directory as audioplayer.py
FileNotFoundError: [Errno 2] No such file or directory: 'hey.wav'
If I remove the hey.wav in the main script, it runs fine. It just doesn't seem to take any arguments.
try this:
call(["python", "C:/Users/Jeff/Documents/audioplayer.py", "C:/Users/Jeff/Documents/hey.wav"])
When you run the last one, the dir is the same with the main.py instead of the audioplayer.py.
I'm trying to start another script in python and then give an answer to input, this is the main script:
import subprocess
import sys
import platform
cmdline = ['py', 'ciao.py']
cmd = subprocess.Popen(cmdline, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
for line in cmd.stdout:
if line == b'Loading...\r\n':
print("sending data...")
cmd.communicate(b"test\n")[0]
print("done")
print(line)
print(line)
And this is ciao.py:
import os
import re
import time
print("Loading...")
ciao = input("> ")
print(ciao)
os.system("mkdir okfunziona")
print("Done")
while 1:
time.sleep(10)
The main script manages to send "test" but then hangs and does not print "done" to the console.
The problem is both on windows and on linux.
---------------------------------------------------------------EDIT--------------------------------------------------------------
Ok i have tested Ashish Nitin Patil's example but i see b'Loading...\r\n' output, and I do not see the other outputs of the secondary script, like ">" or "Done", it seems that the "cmd.stdout.readline ()" works only the first time because the script does not end.
See this answer (and others on that question) for inspiration. For your case, you should not be using communicate, instead use stdin.write and stdout.readline.
Your main script might look like below -
while True:
line = cmd.stdout.readline()
print(line)
if line.strip() == b'Loading...':
print("sending data...")
cmd.stdin.write(b"test\n")
cmd.stdin.close()
print("done")
elif line.strip() == b'Done':
break
The outputs -
b'Loading...\n'
sending data...
5
done
b'> test\n'
b'Done\n'
I'm reading from CAT pipe in Linux, using subprocess:
stdout=subprocess.PIPE
so some line has BAD EOL, it's huge file and I want to skip such lines and go for the next one. how I can do this in Python?
PS: I always get:
SyntaxError: EOL while scanning string literal
and seems some socket stopped while writing to that file,because I see really huge spaces in the end of that file. Don't want to fix it, want to skip it
here is my code :
import sys,os
import subprocess
import traceback
import re
import ast
try :
cat = subprocess.Popen(["hadoop", "dfs", "-cat", "PATH TO FILE"], stdout=subprocess.PIPE)
for data in cat.stdout:
data = re.sub(' +',' ',data)
msg= ast.literal_eval(data)
if msg['some_string'] == 'some_string' :
print msg['status']
else :
continue
except :
print traceback.format_exc()
pass
exit()
so the output before the programs exits :
many empty spaces and ...
^
SyntaxError: EOL while scanning string literal
Here, try this:
import sys,os
import subprocess
import traceback
import re
import ast
try :
cat = subprocess.Popen(["hadoop", "dfs", "-cat", "PATH TO FILE"], stdout=subprocess.PIPE)
for data in cat.stdout:
data = re.sub(' +',' ',data)
try:
msg= ast.literal_eval(data)
if msg['some_string'] == 'some_string' :
print msg['status']
else :
continue
except SyntaxError:
continue #skip this line
except :
print traceback.format_exc()
pass
exit()
Hope it helps!
to skip errors you can just code smth like:
try:
your code
except {Your error}:
pass
or
try:
your code
except:
pass
for all errors
you could also use smth like:
import sys
import traceback
try:
{code}
except Exception:
_type, _value, _trace = sys.exc_info()
print "Type:\n\t{0}\nException:\n\t\t{1}\nTraceback:\n\t{2}".format(
_type, _value, traceback.format_tb(_trace))
So, when I run this code in python 2.7.3 with command ./randline.py test.txt this code works fine. However when I try to run this code in python 3 I got an error message "/usr/bin/python: can't open file '3': [Errno 2] No such file or directory"
import random, sys
from optparse import OptionParser
class randline:
def __init__(self, filename):
f = open(filename, 'r')
self.lines = f.readlines()
f.close()
def chooseline(self):
return random.choice(self.lines)
def main():
version_msg = "%prog 2.0"
usage_msg = """%prog [OPTION]... FILE
Output randomly selected lines from FILE."""
parser = OptionParser(version=version_msg,
usage=usage_msg)
parser.add_option("-n", "--numlines",
action="store", dest="numlines", default=1,
help="output NUMLINES lines (default 1)")
options, args = parser.parse_args(sys.argv[1:])
try:
numlines = int(options.numlines)
except:
parser.error("invalid NUMLINES: {0}".
format(options.numlines))
if numlines < 0:
parser.error("negative count: {0}".
format(numlines))
if len(args) != 1:
parser.error("wrong number of operands")
input_file = args[0]
try:
generator = randline(input_file)
for index in range(numlines):
sys.stdout.write(generator.chooseline())
except IOError as (errno, strerror):
parser.error("I/O error({0}): {1}".
format(errno, strerror))
if __name__ == "__main__":
main()
Is there any thing wrong with this code for python 3 interpreter?
Looks like you are running python 3 (with a space). You should use python3 instead.
Since python2.7.3 and python3.* have different syntax, codes work using python2.7.3 and then may not work using python3.*. For example
print 'hello world'
works using python2.7.3 but receives error using python3.*. To run it, we have to use print('Hello world')
So just change the syntax to python3.* format. But my suggestion is to use python2.7.3 to run your code.