I am trying to setup a program where when someone enters a command it will run that command which is a script in a sub folder called "lib".
Here is my code:
import os
while 1:
cmd = input(' >: ')
for file in os.listdir('lib'):
if file.endswith('.py'):
try:
os.system(str(cmd + '.py'))
except FileNotFoundError:
print('Command Not Found.')
I have a file: lib/new_user.py But when I try to run it I get this error:
Traceback (most recent call last):
File "C:/Users/Daniel/Desktop/Wasm/Exec.py", line 8, in <module>
exec(str(cmd + '.py'))
File "<string>", line 1, in <module>
NameError: name 'new_user' is not defined
Does anyone know a way around this? I would prefer if the script would be able to be executed under the same window so it doesn't open a completely new one up to run the code there. This may be a really Noob question but I have not been able to find anything on this.
Thanks,
Daniel Alexander
os.system(os.path.join('lib', cmd + '.py'))
You're invoking new_user.py but it is not in the current directory. You need to construct lib/new_user.py.
(I'm not sure what any of this has to do with windows.)
However, a better approach for executing Python code from Python is making them into modules and using import:
import importlib
cmd_module = importlib.import_module(cmd, 'lib')
cmd_module.execute()
(Assuming you have a function execute defined in lib/new_user.py)
Related
So I am trying to make a download tool to download stuff via a link here is a snippet from my code
if download_choice == "14":
print("Downloading test file to Desktop...")
myfile14 = requests.get(url14)
open('c:/users/%userprofile%/desktop/', 'wb').write(myfile14.content)
I want to make a program that can download stuff via a link. I want it to run on all PCs not only on mine. Here is the error:
Traceback (most recent call last): File "C:\Users\David\Desktop\Windows Download Tool\Python\WDT.py", line 100, in <module> open('c:/users/%userprofile%/desktop/', 'wb').write(myfile14.content) FileNotFoundError: [Errno 2] No such file or directory: 'c:/users/%userprofile%/desktop/'
Python does not use %userprofile% to get the username of the executing user.
To achieve this, you need to import the package os and run it's getlogin function. This returns a string with the current username
Example:
import os
username = os.getlogin()
if download_choice == "14":
print("Downloading test file to Desktop...")
myfile14 = requests.get(url14)
open(f'C:/Users/{username}/desktop/', 'wb').write(myfile14.content)
I am using an f-string for opening the file, since it is preferred by PEP-8 (it's just correct code-styling)
Attention: This only works on a windows machine
I have a python file(file1.py) where i have written a script. Now, my friend asked me to keep the inputs in another python file(file2.py) and import the file in file1.py so that its becomes easy to modify the inputs if we keep it seperate file. So i created file2.py, copied the inputs there and saved it. Then i wrote the following line in file1.py: from file2 import * but its throwing error:
TASK [Run the python script]
********************************************************************************************************************************************************************************************************************************* fatal: [automation_server]: FAILED! => {"changed": true, "msg":
"non-zero return code", "rc": 1, "stderr": "Shared connection to
10.242.174.192 closed.\r\n", "stderr_lines": ["Shared connection to 10.242.174.192 closed."], "stdout": "/etc/profile.d/lang.sh: line 19: warning: setlocale: LC_CTYPE: cannot change locale (UTF-8): No such
file or directory\r\nTraceback (most recent call last):\r\n File
\"/home/bgnanasekaran/.ansible/tmp/ansible-tmp-1591957555.760499-407
182191177023663/download_RI_build.py\", line 8, in \r\n
from file2 import
*\r\nModuleNotFoundError: No module named 'file2'\r\n", "stdout_lines": ["/etc/profile.d/lang.sh: line 19: warning: setlocale:
LC_CTYPE: cannot change locale (UTF-8): No such file or directory",
"Traceback (most recent call last):", " File
\"/home/bgnanasekaran/.ansible/tmp/ansible-tmp-1591957555.760499-407
182191177023663/download_RI_build.py\", line 8, in ", "
from file2 import *", "ModuleNotFoundError: No module named 'file2'"]}
Note: I'll give some example of inputs in file2.py -
name="Suresh"
college="VIT"
Also note: I wrote all these python scripts to make it run with ansible playbook. This script is a part of play in my ansible playbook.
Please help me do this. I want a python file where i can store my python script inputs and use the same file in python script. This is not so related to ansible but more related to python.
you need a configuration file this post might help you or you can create a class and all required variable as a class variable and import the class into your script.
import is for python files only.
If you want to read content of a file you need to open it.
with open('filename', 'r') as handler:
print(handler.readlines())
Is a minimal example
You could also try to use environment varibales, which is a much more common practice when dealing with deployment strategies
import os
VARIABLE = os.getenv('VARIBALE', 'default_value')
Then you run the script with:
VARIABLE=this ./pythonscript.py
Or export the variable into the environment in another way
So, in short, I created a script (named main.py) in which there was a moment where I wrote in a file. It worked well. However, the permissions on this file had to be rwxrwxrw- and hence anyone could modify the file on the server. That's not what I wanted. So I changed the permissions to rwxrwxr-- and then I changed the code of main.py :
#!/usr/bin/python
import subprocess
text = "I want this text to appear in my file"
command = subprocess.Popen(["python", "modificateFile.py", str('"')+text+str('"')], stderr=subprocess.PIPE, stdout=subprocess.PIPE) #I run another file that will do the task
for i in command.stderr:
print(i.decode("utf-8")) #check if there is any error
code of modificateFile.py
#!/usr/bin/python
import platform
import os
import sys
UID = 1080 #my UID.. I don't really know if it's the right way to program this
if __name__ == "__main__":
system = platform.system()
if system == "Linux": #ok it may be useless
os.setuid(UID) # /!\ I THINK THAT'S WHERE THE PROBLEM IS /!\
if len(sys.argv) > 1:
with open("file.txt", "w", encoding="utf-8") as f:
f.write(sys.argv[1])
else:
sys.stderr.write("not enough parameters to work") #didn't know which error I could raise..
#so as I already imported sys, I used this function
exit(-1)
else:
sys.stderr.write("wrong OS : program only work on linux")
exit(-1)
When I created this, I didn't know really what I was doing to be honest… I am learning programming.
Error message:
Traceback (most recent call last): File "modificateFile.py", line 11,
in os.setuid(UID) PermissionError: [Errno 1] Operation not permitted
I heard of SUID.. but I don't have root permissions.
Could someone explain what is wrong and what I could do ?
(if you need more elements, tell me it)
ok…. I thought SUID was only available for root programs… I had already tested it for this program but it didn't work. However, I learnt after that SUID is not available for programs with a shebang at the beginning… So, I created a code in C to do that.
I am trying to find a specific pathname and pass this into os.chdir so I can run a command in that directory. I won't know the exact pathname hence why I have to run the find command. I have tried several ways to do this and each comes with a new error. The code below is one of the ways I have tried, can anyone suggest the best way to do this? Or how to fix this error?
Source Code:
import os
import subprocess
os.system('find ~ -path "*MyDir" > MyDir.txt')
output = subprocess.check_output("cat MyDir.txt", shell=True)
os.chdir(output)
os.system("file * > MyDir/File.txt")
The error:
Traceback (most recent call last):
File "sub1.py", line 8, in <module>
os.chdir(output)
FileNotFoundError: [Errno 2] No such file or directory: b'/Users/MyhomeDir/Desktop/MyDir\n'
I know that directory exists and presume it has something to do with the b' and \n'. I just don't know what the problem is.
Get rid of the \n with strip:
output = subprocess.check_output("cat MyDir.txt", shell=True).strip()
os.chdir(output)
I am working on creating a WebGL interface for which I am trying to convert FBX models to JSON file format in an automated process using python file, convert_fbx_three.py (from Mr. Doob's GitHub project) from command line.
When I try the following command to convert the FBX:
python convert_fbx_three.py Dolpine.fbx Dolpine
I get following errors:
Error in cmd:
Traceback (most recent call last):
File "convert_fbx_three.py", line 1625, in <module>
sdkManager, scene = InitializeSdkObjects()
File "D:\xampp\htdocs\upload\user\fbx\FbxCommon.py", line 7, in InitializeSdkObjects
lSdkManager = KFbxSdkManager.Create()
NameError: global name 'FbxManager' is not defined
I am using Autodesk FBX SDK 2012.2 available here on Windows 7.
Can you please try the following:
import FbxCommon
.
.
.
lSdkManager, lScene = FbxCommon.InitializeSdkObjects()
You probably need to add environment variables pointing to the folder that contains fbx.pyd, FbxCommon.py, and fbxsip.pyd prior to calling anything in those modules.