So basically, I am trying to run some preliminary tests for a website I will be building.
There will be downloads through the site, possibly for the same resource by different users, possibly nearly or at the same time. I want to implement a lock manager of sorts to prevent repeated downloads of a resource when one is already in progress.
The test I am running is just to see if this is even possible. What I am specifically testing for right now is if I begin running a program, if I attempted to open the program again would it open a completely new instance or go to the already open instance. I am doing to this to try and see if user 1 makes changes in their program, if the second user opens their program, they will see those change; otherwise they might not see the changes if they open up a completely new instance of a program.
PHP
exec(escapeshellcmd("C:\Program Files\Python 3.7\python.exe Test2Php.py 0 Testing"), $o1, $r);
echo $r;
var_dump($o1);
Python
#!/usr/bin/env python
import sys
arr = []
t = sys.argv[1]
if (t == '0'):
arr = [sys.argv[k] for k in range(2, len(sys.argv))]
print("if")
else:
print(str(len(arr)))
The problem is the script doesn't return any output at all! It doesn't run either. I tested this by having the python program write a file at the end of successful execution. I have tried shell_exec, passthru, etc. The program itself works when run through command line, but not in any scripts I have made.
I am using a WAMP server on windows.
EDIT:
For anyone else dealing with this. Make sure you have the default Python package in your system path variable. You can do this easily by installing the latest version of python and choosing add to system path. Uninstall anaconda or whatever else may be in the way of the system path and enjoy.
Also make sure you find where the python exe is and use the full path to it.
Your list comprehension will get out of range since you can never do lst[len(lst)] without getting an IndexError. The str() wrapper isn't necessary to print len(arr).
Instead, use a slice of [:2] to remove the first 2 elements:
#!/usr/bin/env python
import sys
arr = []
t = sys.argv[1]
if t == '0':
arr = sys.argv[2:]
print("if")
else:
print(len(arr))
Related
I'll want to know how to call a function in vs code. I read the answer to similar questions, but they don't work:
def userInput(n):
return n*n
userInput(5)
And appends nothing
def Input(n):
return n*n
And in the terminal:
from file import *
from: can't read /var/mail/file
Can somebody help me?
You are doing everything correctly in the first picture. In order to call a function in python on vs code you first have to define the function, which you did by typing def userInput(n):. If you want to see the result of your function, you should not use return, you should use print instead. Return is a keyword- so when your computer reaches the return keyword it attempts to send that value from one point in your code to another. If you want to see the result of your code, typing print (n) would work better.
Your code should look like this:
def userInput(n):
print (n * n)
userInput(5)
The code would print the result 25
Your terminal is your general way to access your operating system, so you have to tell it that you want it to interpret your Python code first.
If you want to run the file you're typing in, you have to first know the location of that file. When you type ls in your terminal, does the name of your Python file show up? If not, hover over the tab in VSCode (it's close to the top of the editor) and see what path appears. Then in your terminal type cd (short for "change directory") and then the path that you saw, minus the <your filename here>.py bit. Type ls again, and you should see your Python file. Now you can type python <your filename here>.py to run it (provided you have Python installed).
You could also run the IDLE by just typing python in your terminal. This will allow you to write your code line-by-line and immediately evaluate it, but it's easier to write in VSCode and then run it with the method I described before.
Can someone help me with this please?
I am trying to compile a program in this case programmed in python that I can run in win9Xdos, that I can call/start from a 9xDos batchfile, that will find the Current working Dir & by that I mean identify the cwd (current working directory) from where the python program and batchfile are executed. The python program will be called getcwd.py which I am hoping someone will outline what I need to do to convert to EXE/COM file. there is a program called Py2EXE but not sure if this will compile for Ms-dos file. Anyways heres my simple code thus far. Can someone tell me if I am on the right track please? Oh by the way what I am trying to do is find the CWD & inject the resultant path into a variable that can be read from 9Xdos. The current Var would be %cwd%
# importing os module
import os
# some websites say use: del cwd (to remove variable if it exists)
cwd = none
cwd = os.getcwd()
print(cwd)
The print line may need interchanging with code below, not sure help needed:
print(type(path))
# <class 'str'>
would the above code work, say in the root e.g. C:\ with & work in obtaining the CWD variable & if correct how would I proceed to compile it to an exe/com file? do I need to take into account LFN's & Spaces between possible paths e.g C:\Program Files & possible backslashes etc?
Your code isn't perfect but it is on the right track. All you need is this:
import os
if __name__ == '__main__':
print(os.getcwd())
There is no need for an auxiliary variable, and I don't know what websites are recommending that you delete the variable before creating it. Trying to delete a nonexistent Python variable is a runtime error. So I would stay away from those websites.
But your question is about setting an environment variable. Calling print() won't do that. All it will do is echo the current working directory to the console. There is no way to change the environment of a running process that will affect the parent process. This is not a Python restriction nor a Windows restriction: it is quite general. The OS sets up the environment of the process when it creates the process. You can make changes to the environment (using os.environ[env-var]) but those changes will only be visible inside that Python process and will not be visible to the environment of the batch file that runs the Python program. To do that, you need to pass the value back to the calling process.
One way to do that is like this:
In Python:
import os
if __name__ == '__main__':
print(f"set CWDIR={os.getcwd()}", file=open("mycd.bat","w"))
I haven't had a Python 1.5.2 environment for 15 years, so I can't test this, but I think the equivalent would have been
if __name__ == '__main__':
print >> open("mycd.bat","w"), "set CWDIR=%s" % (os.getcwd(),)
In a cmd.exe console:
call mycd.bat
Though if your Win9XDos doesn't provide %cd% (which, as far as I recall, was available in MS-DOS 5, or maybe further back still) there is no way of telling if it supports call either. (Are you maybe running command.com instead of cmd.exe? That would explain why things that should be there are missing).
I used pyinstaller to create a 64-bit .exe and that resulted in a file of about 6MB. Now, 32-bit executables are smaller, but it might be that the resulting executable is still too big to load.
So I think the Python route may turn out to be more trouble than it is worth.
I am currently trying to run a .py file but in a loop.
Just for a test I am using
I = 0
while I<10:
os.pause(10)
open(home/Tyler/desktop/test.py)
I = I + 1
I am sure this is a very simple question but I can't figure this one out.
I would also like to add in the very end of this I have to make this run infinitely and let it run for some other things.
There are a few reasons why your code isn't working:
Incorrect indentation (this may just be how you copied it on to StackOverflow though).
Using os without importing it.
Not using quotes for a string.
Mis-using the open function; open opens a file for reading and/or writing. To execute a file you probably want to use the os.system.
Here's a version that should work:
import os
i = 0
while i < 10:
os.pause(10)
os.system("home/Tyler/desktop/test.py")
i += 1
Python is indentation-sensitive, and your code is missing indentation
after the while statement!
Running the open command will not run the Python script. You can
read what it does here in the docs:
https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files
This stack overflow question talks about how to run Python that's
stored in another file
How can I make one python file run another?
I recommend wrapping the code you want to run in a function, e.g.
def foo():
print 'hello'
and then saving this in foo.py. From your main script, you can then do:
import foo
i = 0
while i < 10:
foo.foo()
i += 1
If you want to run something in an infinite loop, you need the condition for the while loop to always be true:
while True:
# do thing forever
A note on importing: The example I have given will work if the foo.py file is in the same directory as the main Python file. If it is not, then you should have a read here about how to create Python modules http://www.tutorialspoint.com/python/python_modules.htm
I'm having more than a little trouble running a python script from an AIR application using the NativeProcess interface. In theory, this should be quite simple. Adobe even uses this as their example in the ActionScript 3.0 documentation for NativeProcess, as follows:
var nativeProcessStartupInfo:NativeProcessStartupInfo = new NativeProcessStartupInfo();
var file:File = File.applicationDirectory.resolvePath("test.py");
nativeProcessStartupInfo.executable = file;
They even include the contents of what test.py might include:
#!/usr/bin/python
# ------------------------------------------------------------------------------
# Sample Python script
# ------------------------------------------------------------------------------
import sys
for word in sys.argv: #echo the command line arguments
print word
print "HI FROM PYTHON"
print "Enter user name"
line = sys.stdin.readline()
sys.stdout.write("hello," + line)
The problem is that, as far as I can see, this simply doesn't work. I get the following error when I attempt it:
Error #3219: The NativeProcess could not be started. '%1 is not a valid Win32 application.
Presumably the latest version of AIR (19.0) doesn't allow the execution of anything without an "exe" file extension. The following code does seem to do what I want:
var nativeProcessStartupInfo:NativeProcessStartupInfo = new NativeProcessStartupInfo();
var file:File = new File("C:/Python/Python35/python.exe");
nativeProcessStartupInfo.executable = file;
nativeProcessStartupInfo.workingDirectory = File.applicationDirectory.resolvePath(".");
var processArgs:Vector.<String> = new Vector.<String>();
processArgs[0] = "test.py";
nativeProcessStartupInfo.arguments = processArgs;
The problem here is twofold. First, you need to know the absolute path to the executable, which I can't assume. Second, the code is no longer platform independent. The file extension would be something else on Linux or Mac.
I thought I might solve the first problem by requiring a %PYTHON_PATH% environment variable and then making the executable dependent on that. However, I can't figure out a way to use an environment variable within the ActionScript File object. It "helpfully" escapes all the "%" characters before ever sending something to the command line.
At this point this fairly simple problem has turned into a showstopper. Could someone help me understand a way to either:
Execute something with the "py" extension with NativeProcess
Successfully resolve a path that depends on an environment variable in the File object?
So I have this uber script which constantly checks the system path for a program (openvpn). When you install openvpn it adds itself to the system path. I run my script in the console and, while it runs and checks, I install openvpn. In that console my script will never find openvpn in sys path. If I open a new console and run the same script it finds it.
Any idea how I can make my script a little less dumb?
import os
import time
import subprocess
def cmd( command ):
return subprocess.check_output( command, shell = True )
def program_in_path( program ):
path = cmd( "path" ).split(";")
for p in path:
if "openvpn" in p.lower():
return True
return False
if __name__ == '__main__':
while True:
print program_in_path("openvpn")
time.sleep( 2 )
I presume it's from the shell = True thing but how else would I find it if not with path or WHERE openvpn /Q ? Running with no sehll I get WindowsError: [Error 2] The system cannot find the file specified
Here's slightly the same program done in ruby which works 100%:
loop do
puts system( "WHERE openvpn /Q" )
sleep( 5 )
end
Unfortunately my project is too deep into python to switch languages now. Too bad.
It's actually because when your program starts, it has an environment configured. Part of that environment is the system path. When you start a subshell, it inherits the environment of the parent process.
I'm not a Windows programmer, and I don't have a Windows machine available to test on right now. But according to that bug report, if you import nt in your script and reload(nt) in your while True loop that it will pull down a fresh copy of the environment from the system. I don't know whether that's true or not. It might be worth a try.
For what it's worth, you can see the same behavior from the cmd window by, for instance, opening a command window, adding a program folder to the System Path, and then trying to run an exe from that program folder in your existing cmd window. It won't work -- but open a new cmd window, and it will.
The bug report you cite is about a different problem. That problem outlined there is that from within Python, if you load in one of the system DLLs and use a particular function Windows provides for manipulating your environment, Python does not reflect the change. However, if you make a change to os.environ, Python recognizes that change. The conclusion from the community was that the particular function that the reporter was using, was not the correct function to use to get the results he expected.
Perhaps this approach works for you, getting the PATH variable straight from the registry (since you're on Windows).
For instance you could do something like this:
import winreg
def PathFromReg():
loc = r'SYSTEM\CurrentControlSet\Control\Session Manager\Environment'
reg = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE)
key = winreg.OpenKey(reg, loc)
n_val = winreg.QueryInfoKey(key)[1]
for i in range(n_val):
val = winreg.EnumValue(key, i)
if val[0] == 'Path':
return val[1]
path = PathFromReg()
print('openvpn' in path.lower())
I think you only need to assign the key once and then query the values inside the loop.
Note: In Python 2 the module is called _winreg.