Today, I was testing my old python script, it was about fetching some details from an API and write then in a file. Until my last test it was working perfectly fine but today when I executed the script it worked, I mean no error at all but it neither write nor created any file. The API is returning complete data - I tested on it terminal, then I created another test.py file to check if file write statements are working, so the result was - they were not working.
I don't know what is causing the issue, it also ain't giving any error.
This is my sample TEST.PY file
filename = "domain.log"
with open(filename, 'a') as domain_file:
domain_file.write("HELLO\n")
domain_file.write("ANOTHER HELLO\n")
Thank you
Using 'a' on the open call to open the file in append mode (as shown in your code) should work just fine.
I don't think your issue is on the Python side. The next thing to check are your directory permissions:
$ ls -al domain.log
-rw-r--r-- 1 taylor staff 60 Apr 16 07:57 domain.log
Here's my output after running your code a few times:
$ cat domain.log
HELLO
ANOTHER HELLO
HELLO
ANOTHER HELLO
HELLO
ANOTHER HELLO
It may be related to file permission or its directory. Use ls -la to see file and folder permissions.
Related
I would like to save the input code and the output result into a file. For example the following python code code.py:
print(2+2)
print(3+2)
to create a code-and-output.txt:
>>> print(2+2)
4
>>> print(3+2)
5
But I can not get it working. Basically, I want to code-and-output.txt to capture what would happen if I run interpreted python and run statements in python interactive environment (code + output).
Ways that I have tried so far:
Redirect stdout:
python code.py > code-and-output.txt
It only saves the output.
Redirect stdout and stdin:
python < code.py > code-and-output.txt
It does the same (only output).
nohup
nohup python code.py
The same problem: only output.
Script
script -q code-and-output.txt
python
print(2+2)
print(2+3)
ctr+d
ctr+d
It works but I need to do it manually. Moreover, it saves some garbage that I can not make them quiet with -q.
Bash Script
# bash-file.sh
python &
print(2+2)
print(2+3)
Does not work: commands run in console bash, not python. It does not work with & either: never ends python repl.
Using tty
open another terminal like /dev/pts/2 and send above bash-file.sh
cat bash-file.sh > /dev/pts/2
It just copies but does not run.
I am not interested in solutions like Jupyter and iPython. They have their own problems that does not address my requirement.
Any solution through linux commands (preferably) or python? Thank you.
Save this is as repl_sim.py in the same directory as your code.py:
with open("code.py", 'r') as input_file:
for line in input_file:
print(f">>> {line.strip()}")
eval(line)
Then run in your terminal with the following if you want to redirect the output to a text file named code-and-output.txt:
python repl_sim.py > code-and-output.txt
-OR-
Then run in your terminal with the following if you want to see the output as well as the make the text file matching:
python repl_sim.py | tee code-and-output.txt
It at least works for the example you provided as code.py.
Pure Python version of first option above so that you don't need shell redirect.
Save this code as repl_sim.py:
import contextlib
with open('code-and-output.txt', 'w') as f:
with contextlib.redirect_stdout(f):
with open("code.py", 'r') as input_file:
for line in input_file:
print(f">>> {line.strip()}")
eval(line)
Then run in your terminal with:
python repl_sim.py
That will result in code-and-output.txt with your desired content.
Contextlib use based on Raymond Hettinger's August 17th 2018 Tweet and contextlib.redirect_stdout() documentation
.
Trying to get robot framework to properly be able to validate the result of a basic .py file.
I have a simple Hello World python file in a resource directory.
My .robot file looks like this:
*** Settings ***
Library Process
*** Test Case ***
We should print to a command line.
${result}= run process python -c ../Resources/helloWorld.py
Should Be Equal ${result.stdout} Hello World.
The helloWorld.py file is just print("Hello World.")
Directory structure would look like this:
Root
-tests
--test.robot
-Resources
--hellowWorld.py
But when I execute the test I receive a fail with the result: != Hello World.
Found that it wasn't able to find the directory using relative path, ended up needing to use the full path.
stdout was just logging | FAIL |
So I logged the stderr and found that it was throwing a syntax error. After some trial and error of tweaking the path and escaping all my slashes, it was able to run how I was expecting it to.
First of all, I suggest you use "log" to see what your "${result}" is, I doubt that the robot can get the content that you printed in python. Second, I think you should try "Should Be Equal As Strings"
I am absolutely new to ubuntu and cron.
I want to run some scripts:
I edited and saved the crontab file:
37 13 30 6 * /media/xxx/xxx/bin/python /home/xxx/PycharmProjects/testcron.py
testcron.py code:
print('Hellow World')
input('Test Success')
I assumed that this would show me if the cronjob ran.
But no window popped up on the time I set.
Can someone point me to how to check if it ran? Did I configure this wrong?
If you haven't done anything on your system, try looking in
/var/log/syslog
Use grep to filter/search:
grep CRON /var/log/syslog
You can also pipe the output of your cron job to a specific location as well
37 13 30 6 * /media/xxx/xxx/bin/python /home/xxx/PycharmProjects/testcron.p >> /var/log/job.log 2>&1
I always include date >> ~/cronjobname.txt at the end of my cron job scripts. It will keep appending the date and time to that text file every time it runs. Another advantage to this is, If someone runs it manually for any reason (testing, debugging), you will have that timestamp too.
In Python, you can create a testcron.py file that looks like this:
f = open("cool_test", "w")
f.write("")
f.close()
If you run python3 testcron.py, you'll see a cool_test file generated in the same directory as testcron.py.
Now, you can just call testcron.py from a cronjob, and you'll be able to verify the process worked by making sure that cool_file was generated.
I am new at python and learning the language. The following code should create a file in the running program directory and write to it but it doesn't do this at all in a .py file. If I put the same code in the IDLE shell it returns 17. No errors just doesn't create the file. What am I doing wrong?
with open("st.txt", "w") as f:
f.write("Hi from Python!")
Thanks for the help
Mike
This code is flawless, no problem!
I guess that in your REPL shell, the $PWD environment variable is set for somewhere, so your destination file is in some corner.
No exception thrown indicates that no problem with access authority.
Maybe you can set some absolute path string, such as ~/st.txt
By the way, the successful invoke should return 15 instead of 17, totally count 15 chars.
your code works well, st.txt will be touched at executing path.
other ways, your system account can't write in your execute path.
try in your $HOME path to execute your code, I think, It will work well
I have the following situation here. My OS shows that django TemporaryUploadedFile which I got via the POST request does not exist anymore but somehow this uploaded file can be read.
Here is the code
text_file = request.FILES['text_file']
print(text_file.temporary_file_path())
os.system('ls -l ' + text_file.temporary_file_path())
fs = FileSystemStorage()
file_new =fs.save(text_file.name, text_file)
print(text_file.temporary_file_path())
os.system('ls -l ' + text_file.temporary_file_path())
fs.delete(file_new)
for chunk in text_file.chunks():
text += chunk.decode(encoding)
print('Got text OK.')
This gives the following output:
/tmp/tmp0tngal9t.upload foo.txt
-rw------- 1 mine machine 3072889 oct 18 19:29 /tmp/tmp0tngal9t.upload
/tmp/tmp0tngal9t.upload foo.txt
ls: cannot access '/tmp/tmp0tngal9t.upload': No such file or directory
Got text OK.
So TemporaryUploadedFile is disappeared after it was saved to file_new which later is also deleted. Anyway text_file is successfully read by chunks and I get all the text from uploaded foo.txt file. How it is possible? From where text_file.chunks() gets the data if text_file does not exist anymore?
I use:
python 3.5.2
django 1.10.2
ubuntu 16.04.1
I found out that this problem still remains for bare python, so it is not particularly related to django as in this example I just read text_file which were open in request.FILES['text_file'].
I re-asked the similar question here focusing on python only. It turned out that the problem is not so related with python either, but with Linux/Unix system file management. I quote here the answer of Jean-François Fabre:
Nothing to do with Python. In C, Fortran, or Visual Cobol you'd have
the same behaviour as long as the code gets its handle from open
system call.
On Linux/Unix systems, once a process has a handle on a file, it can
read it, even if the file is deleted. For more details check that
question (I wasn't sure if it was OK to do that, it seems to be)
On Windows you just wouldn't be able to delete the file as long as
it's locked by a process.